diff --git a/.github/workflows/client-sync-check.yml b/.github/workflows/client-sync-check.yml index 2892a1b..ee567da 100644 --- a/.github/workflows/client-sync-check.yml +++ b/.github/workflows/client-sync-check.yml @@ -44,7 +44,10 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v4 with: - node-version: '20' + # Must satisfy the JS client's `engines.node` floor: yarn treats a + # mismatch as a hard error and aborts the install. Keep in step with + # dclimate-client-js's own workflows when that floor moves. + node-version: '22' - name: Enable Corepack run: corepack enable diff --git a/README.md b/README.md index 6df49eb..b8b93c5 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,123 @@ Callers loading a direct CID have no STAC resolution mapping and must pass generator's `metadataGroup` is internal catalog-generation configuration and does not influence client selection. +## Entity data usage + +Gridded Zarr datasets come from `load_dataset`. Point-observation **entity** +datasets (GHCND and friends) live under `client.entities`, and read the same way: +degrees, ISO timestamps, chained selections. + +"Entity" is the underlying library's word for the thing a row belongs to — a +weather station in GHCND, a buoy in NDBC. Not every dataset is keyed by a place, +so an entity need not have a position at all, and those simply never match a geo +query. + +Entity support is built on +[`tabular-py`](https://github.com/dClimate/tabular-py), which installs +automatically as a dependency. It is imported as `tabular_py` but distributed as +`dclimate-tabular-py`, because PyPI normalises the name `tabular-py` onto an +unrelated existing project. + +```python +async with dClimateClient() as client: + ghcnd = await client.entities.load("bafyr4i...") + + # Every entity, with position and coverage window. + for e in await ghcnd.list_entities(): + print(e.entity_id, e.latitude, e.longitude, e.start, e.end) + + # Entities within 50 km of a point, over one week. + records = await ( + ghcnd + .circle(40.75, -73.99, 50) + .time_range("2023-01-01", "2023-01-07") + .to_records("TMAX") + ) +``` + +Reads go through the client's own IPFS transport, so pinning, retries, and +configured endpoints apply to entity reads too. Resolution is by CID for now; +STAC catalog support will follow. + +Column names come from the dataset's own schema, uppercased — which is how every +dClimate dataset published so far names them, so `TMAX` and `PRCP` work as +documented. A dataset whose published names are not simply the uppercase of its +stored ones needs its own mapping, passed as `column_key`: + +```python +# The reader's default. Pass a different one only for a dataset that needs it. +mixed = await client.entities.load("bafyr4i...", column_key=lambda f: f.name) +print([c.name for c in mixed.columns()]) # the schema's own names, verbatim +``` + +Each column also states the unit its values are in. Units are documentation, +never an instruction to convert: a GHCND `TMAX` declaring `degC_tenths` really +does return `194` for 19.4 °C. + +An entity can additionally declare windows of its history that are *unknown*, as +distinct from empty — a fetch that failed, say. Without that, zero rows and "no +observations" are indistinguishable: + +```python +plan = await ghcnd.select("USW00023174").time_range("2024-01-01", "2024-12-31").plan() +for entity_id, gaps in plan.gaps: + for gap in gaps: + print(entity_id, gap.reason) # e.g. "awdb: HTTP 500" +``` + +Selections return new instances, so a partial selection can be branched: + +```python +week = ghcnd.time_range("2023-01-01", "2023-01-07") +nyc = await week.select("USW00094728").rows() +lax = await week.select("USW00023174").rows() +``` + +Two things differ from `GeotemporalData`, because the data model differs: + +- **`nearest(lat, lon, max_km=...)` instead of a point selection.** A grid always + has a cell under any coordinate; entities are irregular, so the nearest one may + be far away. Pass `max_km` to make that a hard bound rather than a surprise. +- **`where(...)` has no gridded counterpart.** Row-level predicates are pushed + down to fragment statistics, so most fragments are skipped without being read: + +```python +from tabular_py import gt + +# `nearest` reads the entity index to find the match, so it is awaited -- +# unlike the synchronous selections above. +hot_days = await ( + (await ghcnd.nearest(29.98, -95.36)) + .time_range("2025-01-01", "2025-12-31") + .where(gt("TMAX", 350)) # tenths of °C, so 35 °C + .rows() +) +``` + +`nearest` alone means the nearest *entity*, which is not always the nearest +*usable data*: near downtown Los Angeles the closest station is 0.63 km away and +has never recorded `TMAX`, while the closest that has is 5.4 km away. Ask for the +columns you need, and narrow them to a time range when "has ever reported" is not +good enough: + +```python +# Resolves the dataset and the entity in one call. +nearest = await client.entities.nearest( + "bafyr4i...", + 34.0522, -118.2437, + columns=["TMAX"], + within=("2024-01-01", "2024-12-31"), + max_km=50, +) +print(nearest.entity_id, nearest.km) +``` + +Entity failures arrive as this library's own errors, for the whole chain rather +than just `load`: an unknown column is an `InvalidSelectionError`, a well-formed +query that matched nothing is a `NoDataFoundError`, and bytes that do not +describe a readable dataset are a `DatasetCorruptError`. All descend from +`ZarrClientError`, so one `except` still covers the client. + ## Siren API usage The Python client also exposes a Siren REST client for metrics and regions. diff --git a/dclimate_client_py/__init__.py b/dclimate_client_py/__init__.py index 0586b56..86d7a90 100644 --- a/dclimate_client_py/__init__.py +++ b/dclimate_client_py/__init__.py @@ -35,11 +35,17 @@ ) from .dclimate_zarr_errors import ( ConflictingResolutionSelectionError, + DatasetCorruptError, + DatasetNotFoundError, + InvalidSelectionError, + NoDataFoundError, MultiresolutionSelectionRequiredError, ResolutionNotAvailableError, SirenApiError, + TabularNotInstalledError, X402PaymentError, X402NotInstalledError, + ZarrClientError, ) _LAZY_IMPORTS = { @@ -48,6 +54,8 @@ "dClimateClient": (".dclimate_client", "dClimateClient"), "GeotemporalData": (".geotemporal_data", "GeotemporalData"), "load_stac_catalog": (".stac_catalog", "load_stac_catalog"), + "EntitiesClient": (".entities", "EntitiesClient"), + "WrappedEntityDataset": (".entities", "WrappedEntityDataset"), "list_available_datasets": (".stac_catalog", "list_available_datasets"), } @@ -88,6 +96,11 @@ def __dir__() -> list[str]: "resolve_cid_from_stac_server", "list_available_datasets_from_stac_server", "STAC_SERVER_URL", + "ZarrClientError", + "DatasetCorruptError", + "DatasetNotFoundError", + "InvalidSelectionError", + "NoDataFoundError", "MultiresolutionSelectionRequiredError", "ResolutionNotAvailableError", "ConflictingResolutionSelectionError", @@ -105,4 +118,8 @@ def __dir__() -> list[str]: "SirenApiError", "X402PaymentError", "X402NotInstalledError", + # Entities + "EntitiesClient", + "WrappedEntityDataset", + "TabularNotInstalledError", ] diff --git a/dclimate_client_py/dclimate_client.py b/dclimate_client_py/dclimate_client.py index 2e55e1a..4a3afa0 100644 --- a/dclimate_client_py/dclimate_client.py +++ b/dclimate_client_py/dclimate_client.py @@ -8,6 +8,7 @@ import asyncio import typing from collections.abc import Mapping +from dataclasses import replace if typing.TYPE_CHECKING: import pystac @@ -24,6 +25,7 @@ from .datasets import DatasetMetadata from .dclimate_zarr_errors import ( ConflictingResolutionSelectionError, + DatasetNotFoundError, InvalidSelectionError, MultiresolutionSelectionRequiredError, ResolutionNotAvailableError, @@ -40,6 +42,14 @@ list_versions_from_url, ) from .siren import SirenClient +from .entities import EntitiesClient, WrappedEntityDataset + +if typing.TYPE_CHECKING: # pragma: no cover + from collections.abc import Callable + + from tabular_py import TableField + + ColumnKey = Callable[[TableField], str] from .siren.types import ( SirenMetricDataPoint, SirenMetricQuery, @@ -67,6 +77,11 @@ def _merge_cleanup_error( return new +#: The ``dclimate:layout`` value marking a STAC item as entity +#: (point-observation) data rather than a gridded Zarr store. +ENTITY_DATASET_LAYOUT = "tabular" + + class dClimateClient: """ Async context manager for loading dClimate datasets from IPFS. @@ -170,6 +185,10 @@ def __init__( if siren is not None: self._siren_client = SirenClient(siren) + # Entity datasets. Unlike Siren this needs no configuration, so it is + # built on first access rather than here -- see the `entities` property. + self._entities_client: typing.Optional["EntitiesClient"] = None + async def __aenter__(self) -> "dClimateClient": """Initialize KuboCAS when entering async context.""" # Create KuboCAS with configured endpoints @@ -217,6 +236,19 @@ async def __aexit__(self, exc_type, exc_val, exc_tb): except BaseException as error: cleanup_error = _merge_cleanup_error(cleanup_error, error) + try: + if self._entities_client is not None: + await self._entities_client.aclose() + except BaseException as error: + cleanup_error = _merge_cleanup_error(cleanup_error, error) + finally: + # Dropped, not just closed. It holds the `KuboCAS` closed below, and + # a closed `KuboCAS` never reopens -- so keeping this instance would + # make entity reads after the context fail on a dead transport + # instead of falling back to the gateway, which is what the + # `entities` property promises outside the context. + self._entities_client = None + try: if self._kubo_cas is not None: await self._kubo_cas.__aexit__(exc_type, exc_val, exc_tb) @@ -736,19 +768,25 @@ async def _resolve_dataset_details( async with httpx.AsyncClient( timeout=30, follow_redirects=False ) as client: - return await aresolve_dataset_from_stac_server( + return replace( + await aresolve_dataset_from_stac_server( + collection=resolved_collection, + dataset=dataset, + variant=variant, + server_url=self._stac_server_url, + client=client, + ), collection=resolved_collection, - dataset=dataset, - variant=variant, - server_url=self._stac_server_url, - client=client, ) - return await aresolve_dataset_from_stac_server( + return replace( + await aresolve_dataset_from_stac_server( + collection=resolved_collection, + dataset=dataset, + variant=variant, + server_url=self._stac_server_url, + client=self._get_stac_http_client(), + ), collection=resolved_collection, - dataset=dataset, - variant=variant, - server_url=self._stac_server_url, - client=self._get_stac_http_client(), ) except (httpx.HTTPError, ValueError): pass @@ -782,7 +820,7 @@ async def _resolve_dataset_details( if len(prefixed_matches) == 1: resolved_collection = prefixed_matches[0] - return await asyncio.to_thread( + details = await asyncio.to_thread( resolve_dataset_from_stac, catalog=self._stac_catalog, collection=resolved_collection, @@ -790,6 +828,14 @@ async def _resolve_dataset_details( variant=variant, organization=organization, ) + # The name resolved above is the one the item was actually found under, + # and it is not always the one the caller passed: a unique short name + # expands here (`ghcnd` -> `noaa_ghcnd`). Returned rather than left in + # this local, because callers build `collection`, `slug`, and + # `organization` from it -- and `organization` is derived by splitting + # on `_`, so an unexpanded name does not merely mislabel the collection, + # it silently reports no organization at all. + return replace(details, collection=resolved_collection) async def list_dataset_versions( self, @@ -848,6 +894,174 @@ async def get_dataset_version( commit_id, ) + # ------------------------------------------------------------------ + # Entity (point-observation) datasets + # ------------------------------------------------------------------ + + async def load_entities( + self, + collection: str, + dataset: str, + variant: typing.Optional[str] = None, + organization: typing.Optional[str] = None, + gateway_url: typing.Optional[str] = None, + column_key: typing.Optional["ColumnKey"] = None, + ) -> typing.Tuple["WrappedEntityDataset", DatasetMetadata]: + """Open an entity (point-observation) dataset by catalog name. + + The entity counterpart to :meth:`load_dataset`, and deliberately a + separate method rather than a layout branch inside it. The two return + different types with different query surfaces -- an entity dataset has no + ``point()`` and its ``nearest()`` can find nothing -- so folding them + together would widen ``load_dataset``'s return to a union and make every + existing gridded caller narrow before calling a Zarr method. Callers know + which kind they want; the entry point says so. + + Resolution is the same STAC lookup :meth:`load_dataset` performs, so a + dataset is addressed the same way here as anywhere else in the library, + and the release metadata comes back alongside it. That matters more for + entity data than for gridded: ``commit_id`` and ``stream_id`` identify + the exact snapshot a query ran against, which is what lets a caller + re-resolve it later rather than silently getting whatever is newest. + + Columns are named by the schema's own field names unless ``column_key`` + is given. That mapping is a property of a dataset's publishing profile + (GHCND stores ``tmax`` and publishes ``TMAX``), and nothing readable + from here states it, so it is the caller's to pass rather than this + method's to guess. + + Raises + ------ + DatasetNotFoundError + If the resolved item is not tabular. A gridded collection named here + is a caller mistake worth reporting in terms of the fix, not a + manifest parse failure deep inside the reader. + """ + resolved = await self._resolve_dataset_details( + collection=collection, + dataset=dataset, + variant=variant, + organization=organization, + ) + # Taken from the resolution rather than recomputed here: resolution can + # expand a unique short name against the catalogue (`ghcnd` -> + # `noaa_ghcnd`), which the organization-prefix rule below cannot know + # about. Falling back to that rule keeps the old behaviour for the + # resolvers that report no identity of their own. + resolved_collection = resolved.collection or collection + if ( + resolved.collection is None + and organization + and not collection.startswith(f"{organization}_") + ): + resolved_collection = f"{organization}_{collection}" + + # Checked rather than assumed: the catalog holds both kinds, and the CID + # of a Zarr store handed to the entity reader fails as a corrupt-dataset + # error that says nothing about the actual mistake. + # + # Positive match, not "absent or tabular". Entity support postdates + # `dclimate:layout`, so an item without the field is a gridded one from + # before the convention -- treating absence as permission would admit + # exactly the Zarr items this guard exists to catch, in order to + # accommodate legacy entity items that cannot exist. + if resolved.layout != ENTITY_DATASET_LAYOUT: + found = resolved.layout or "gridded" + raise DatasetNotFoundError( + f"{collection}/{dataset} is a '{found}' dataset, not an entity " + "dataset. Use load_dataset() for gridded data." + ) + + # `column_key` is forwarded only when given, so the reader's identity + # default stands. + # + # No default is supplied here, deliberately. `column_key` renames + # columns; it does not gate access to them. Without one, every column is + # still readable under the schema's own field names -- which are what + # the dataset actually stores, so they are never wrong. Supplying a + # default would only be guessing at the spelling a dataset's publishing + # profile uses, and a wrong guess renames columns silently rather than + # failing. + # + # The profile is not derivable here either: tabular deliberately stores + # the schema's names rather than the writer's rendering, precisely so a + # reader is not bound to one profile's casing, and STAC does not carry + # the mapping. So a caller wanting the published spelling passes it, the + # same as with `entities.load(cid)`. + entity_dataset = await self.entities.load( + resolved.cid, + gateway_url=gateway_url, + **({} if column_key is None else {"column_key": column_key}), + ) + + metadata: DatasetMetadata = { + "collection": resolved_collection, + "dataset": dataset, + "variant": resolved.variant, + "slug": ( + f"{organization}/{resolved_collection}/{dataset}/{resolved.variant}" + if organization + else f"{resolved_collection}/{dataset}/{resolved.variant}" + ), + "cid": resolved.cid, + "url": None, + "timestamp": None, + "source": "stac", + "organization": organization + or ( + resolved_collection.split("_")[0] + if resolved_collection and "_" in resolved_collection + else None + ), + } + if resolved.versions_api is not None: + metadata["versions_api"] = resolved.versions_api + if resolved.provenance_api is not None: + metadata["provenance_api"] = resolved.provenance_api + if resolved.citation_api is not None: + metadata["citation_api"] = resolved.citation_api + if resolved.stream_id is not None: + metadata["stream_id"] = resolved.stream_id + if resolved.commit_id is not None: + metadata["commit_id"] = resolved.commit_id + if resolved.version_label is not None: + metadata["version_label"] = resolved.version_label + if resolved.is_citable is not None: + metadata["is_citable"] = resolved.is_citable + if resolved.retention_class is not None: + metadata["retention_class"] = resolved.retention_class + + return entity_dataset, metadata + + @property + def entities(self) -> EntitiesClient: + """Entity datasets, e.g. ``await client.entities.load(cid)``. + + Unlike :attr:`siren`, this needs no configuration -- it reads over the + transport the client already has, so requiring an option would be + ceremony with nothing behind it. + + Reads prefer the client's own ``KuboCAS`` when the client is open, so + pinning, retries, and configured endpoints apply to entity reads too. + Outside the async context there is no ``KuboCAS`` yet, so this falls back + to the plain HTTP gateway -- which is why the instance is rebuilt if it + was first created before ``__aenter__``. + """ + cas = self._kubo_cas + current = self._entities_client + if current is None or current._cas is not cas: + replacement = EntitiesClient( + gateway_url=self._catalog_gateway_base_url, + cas=cas, + ) + if current is not None: + # The replacement inherits any gateway sources the old instance + # opened. It is the only one `__aexit__` closes, so without this + # those connection pools would leak. + replacement._adopt_sources_from(current) + current = self._entities_client = replacement + return current + # ------------------------------------------------------------------ # Siren REST API methods # ------------------------------------------------------------------ diff --git a/dclimate_client_py/dclimate_zarr_errors.py b/dclimate_client_py/dclimate_zarr_errors.py index c23f5a8..eb9fb44 100644 --- a/dclimate_client_py/dclimate_zarr_errors.py +++ b/dclimate_client_py/dclimate_zarr_errors.py @@ -89,6 +89,18 @@ class ConflictingResolutionSelectionError(InvalidSelectionError): """Raised when both resolution and raw Zarr group are provided.""" +class DatasetCorruptError(ZarrClientError): + """Raised when the stored dataset is malformed, rather than the request against it. + + Distinct from :class:`InvalidSelectionError` because the two point at + different culprits. An invalid selection is the caller's to fix by asking + differently; this says the bytes behind the CID are inconsistent, so no + rephrasing helps and the dataset's publisher is who needs to know. Reporting + it as a bad selection would send a caller hunting for a mistake in their own + query. + """ + + class VariantNotFoundError(ZarrClientError): """Raised when specified variant is not found in dataset""" @@ -112,3 +124,7 @@ class X402PaymentError(ZarrClientError): class X402NotInstalledError(ZarrClientError): """Raised when x402 auth is configured but the x402 package is not installed""" + + +class TabularNotInstalledError(ZarrClientError): + """Raised when entity data is requested but tabular-py is not installed""" diff --git a/dclimate_client_py/entities/__init__.py b/dclimate_client_py/entities/__init__.py new file mode 100644 index 0000000..23e501d --- /dev/null +++ b/dclimate_client_py/entities/__init__.py @@ -0,0 +1,22 @@ +"""Entity (point-observation) dataset support, built on ``tabular_py``. + +"Entity" is tabular's word for the thing a row belongs to -- a weather station in +GHCND, a buoy in NDBC -- and this namespace follows it rather than keeping an +older ``station`` vocabulary the layer beneath no longer uses. + +``tabular_py`` is imported lazily, at load time rather than here. It is an +ordinary dependency, so it should always be present; deferring the import keeps +importing this library cheap, and keeps a broken or partial install from taking +down every other namespace along with entity support. +""" + +from .entities_client import EntitiesClient +from .errors import translate_entity_error +from .wrap import WrappedEntityDataset, wrap_entity_dataset + +__all__ = [ + "EntitiesClient", + "WrappedEntityDataset", + "translate_entity_error", + "wrap_entity_dataset", +] diff --git a/dclimate_client_py/entities/entities_client.py b/dclimate_client_py/entities/entities_client.py new file mode 100644 index 0000000..80d4af2 --- /dev/null +++ b/dclimate_client_py/entities/entities_client.py @@ -0,0 +1,246 @@ +"""Entity (point-observation) datasets, as opposed to the gridded Zarr datasets. + +Mirrors ``dclimate-client-js`` ``src/entities/entities-client.ts``. + +"Entity" is tabular's word for the thing a row belongs to -- a weather station in +GHCND, a buoy in NDBC -- and this namespace follows it rather than keeping an +older ``station`` vocabulary the layer beneath no longer uses. + +The two are different enough underneath -- irregular entities with per-entity +time coverage, versus a regular lat/lon/time grid -- that sharing one loader +would help nobody. What they do share is how a caller wants to *ask*: degrees, +ISO timestamps, chained selections. ``EntityDataset`` provides that surface, so +this namespace stays thin: resolve a root, hand back the dataset. + +Resolution is by CID only for now. There is no STAC equivalent for entity data +yet; when there is, ``load`` grows a ``collection``/``dataset`` form alongside +the CID and the rest of this file is unaffected. +""" + +from __future__ import annotations + +import typing + +from ..dclimate_zarr_errors import ( + DatasetNotFoundError, + TabularNotInstalledError, +) +from .errors import translate_entity_error +from .wrap import WrappedEntityDataset, wrap_entity_dataset + +if typing.TYPE_CHECKING: # pragma: no cover + from collections.abc import Callable, Sequence + + from py_hamt import KuboCAS + from tabular_py import NearestEntity, TableField + from tabular_py.entity_dataset import TimeInput + + ColumnKey = Callable[[TableField], str] + + +def _require_tabular() -> typing.Any: + """Import ``tabular_py``, or say plainly that it is missing. + + An ordinary dependency, so this should never fire in a correctly installed + environment. It exists because the import name and the distribution name + differ -- ``tabular_py`` from ``dclimate-tabular-py`` -- which makes the + stock ``ModuleNotFoundError`` name a package that ``pip install`` cannot + find. + """ + try: + import tabular_py + except ImportError as cause: + raise TabularNotInstalledError( + "Entity data requires the `tabular_py` module, which ships in the " + "`dclimate-tabular-py` distribution. Reinstall this package, or " + "install it directly with:\n" + " uv pip install dclimate-tabular-py" + ) from cause + return tabular_py + + +class EntitiesClient: + """Loads entity datasets by CID. + + Reads go through whichever transport the parent client already holds -- its + ``KuboCAS`` when there is one, so pinning, retries, and configured endpoints + apply here too, and a plain HTTP gateway otherwise. + """ + + def __init__( + self, + *, + gateway_url: str, + cas: KuboCAS | None = None, + ) -> None: + self._gateway_url = gateway_url + self._cas = cas + self._owned_sources: list[typing.Any] = [] + # Gateway sources are reused per URL rather than opened per call: each + # one owns an httpx client with its own connection pool, and a + # long-lived client answering a query per request would otherwise hold + # every pool it ever opened until `aclose`. Keyed by the URL because + # that is what makes two sources interchangeable. + self._sources_by_gateway: dict[str, typing.Any] = {} + + def _adopt_sources_from(self, other: EntitiesClient) -> None: + """Take over another instance's open sources, so they still get closed. + + Used when the parent client rebuilds this namespace onto a different + transport. Building the replacement happens in a property, which cannot + await, so the sources the old instance opened move here rather than + being closed on the spot -- otherwise they would leak, since the + replacement is the only instance the parent client still closes. + """ + self._owned_sources.extend(other._owned_sources) + other._owned_sources = [] + # The cache moves with the sources it points at; leaving entries behind + # would hand out a source this instance no longer closes. + self._sources_by_gateway.update(other._sources_by_gateway) + other._sources_by_gateway = {} + + def _source(self, gateway_url: str | None) -> typing.Any: + tabular = _require_tabular() + # A per-request gateway override means a dedicated source; otherwise + # prefer the client's own CAS, which is already configured and pooled. + if gateway_url is None and self._cas is not None: + return tabular.CasRangeSource(self._cas) + url = gateway_url or self._gateway_url + cached = self._sources_by_gateway.get(url) + if cached is not None: + return cached + source = tabular.GatewayRangeSource(url) + # Gateway sources own an httpx client, so they have to be closed; CAS + # sources borrow the client's and must not be. + self._owned_sources.append(source) + self._sources_by_gateway[url] = source + return source + + async def load( + self, + cid: str, + *, + gateway_url: str | None = None, + column_key: ColumnKey | None = None, + ) -> WrappedEntityDataset: + """Open an entity dataset by root CID. + + Reads go through the IPFS HTTP gateway, so this needs no local daemon. + + ``column_key`` maps each schema field to the column name queries and + results use. A dataset's published column names are a property of its + profile, not of the stored blocks: GHCND stores a field named ``tmax`` + and publishes it as ``TMAX``, NDBC preserves mixed case like ``SwH``. + The reader's default is the identity -- the schema's own field names -- + so without the dataset's mapping the published names are unreachable: + ``elements("TMAX")`` is an unknown element even though every GHCND doc + names it that way. For GHCND, pass ``lambda field: field.name.upper()``. + """ + if not cid: + raise DatasetNotFoundError( + "An entity dataset CID is required. To address a dataset by " + "name instead, use client.load_entities(collection=..., " + "dataset=...)." + ) + + from multiformats import CID + + try: + root = CID.decode(cid) + except Exception as cause: + raise DatasetNotFoundError(f"Not a valid CID: {cid}: {cause}") from cause + + tabular = _require_tabular() + source = self._source(gateway_url) + # Forwarded only when given, so tabular's own `default_column_key` stays + # the default rather than being shadowed by a `None` this layer invented. + mapping = {} if column_key is None else {"column_key": column_key} + # Opening reads and parses the dataset's manifest, so a well-formed CID + # that points at something else fails here rather than at query time. + # Translated like any other reader failure: a caller catching + # `ZarrClientError` should not have to also know tabular-py's hierarchy. + # + # The dataset is wrapped on the way out so that guarantee holds for the + # whole chain, not just this call: `select`, `where`, and `rows` raise + # tabular's errors too, and a caller has no reason to expect the boundary + # to stop at `open`. + try: + return wrap_entity_dataset( + await tabular.EntityDataset.open(source, root, **mapping) + ) + except BaseException as cause: + translate_entity_error(cause) + + async def nearest( + self, + cid: str, + latitude: float, + longitude: float, + *, + columns: Sequence[str] | None = None, + max_km: float | None = None, + within: tuple[TimeInput, TimeInput] | None = None, + gateway_url: str | None = None, + column_key: ColumnKey | None = None, + ) -> NearestEntity: + """The entity nearest a point that actually has the data you asked for. + + Resolves the dataset and the entity in one call, because "which station + should I use for this location" is the question most callers open an + entity dataset to ask, and answering it through :meth:`load` means + knowing that ``nearest`` needs ``columns`` to avoid picking a station + full of nulls. + + ``columns`` restricts the search to entities that actually report every + one of those columns. Without it, "nearest" means nearest *entity*, not + nearest *data* -- a station 40 km away that has never recorded TMAX wins + over one 3,000 km away that has. Presence means the entity reported the + column at some point, not that it reported it recently; pass ``within`` + to narrow that to a time range. + + ``columns`` names columns as this dataset publishes them, so a dataset + needing a ``column_key`` needs it here too -- otherwise every name in + ``columns`` is unknown and the search matches nothing. + + Returns the distance alongside the entity: a dataset with no coverage + near the queried point still has a nearest entity, and the only way to + tell that apart from a good match is how far away it is. + """ + dataset = await self.load(cid, gateway_url=gateway_url, column_key=column_key) + # Already wrapped, so failures here arrive as this library's errors. + return typing.cast( + "NearestEntity", + await dataset.find_nearest_entity( + latitude, + longitude, + max_km=max_km, + require_columns=columns, + within_range=within, + ), + ) + + async def aclose(self) -> None: + """Close gateway sources this client opened. + + A borrowed ``KuboCAS`` is the parent client's to close, so it is left + alone; only sources created here are owned here. + + Every source is closed even if one of them fails, because they hold + separate connection pools: stopping at the first failure would strand + the rest, and the list is cleared up front, so nothing would ever retry + them. The first failure is re-raised once the rest are shut. + """ + sources, self._owned_sources = self._owned_sources, [] + # Dropped alongside the list: a closed source must not be handed to the + # next caller, and reopening on demand is the correct behaviour if this + # client is used again. + self._sources_by_gateway = {} + failure: BaseException | None = None + for source in sources: + try: + await source.aclose() + except BaseException as error: + if failure is None: + failure = error + if failure is not None: + raise failure diff --git a/dclimate_client_py/entities/errors.py b/dclimate_client_py/entities/errors.py new file mode 100644 index 0000000..7795a13 --- /dev/null +++ b/dclimate_client_py/entities/errors.py @@ -0,0 +1,100 @@ +"""Translating ``tabular-py`` failures into this library's error types. + +Mirrors ``dclimate-client-js`` ``src/entities/errors.ts``. + +Entity queries are answered by ``tabular_py``, whose errors descend from its own +base class rather than :class:`ZarrClientError`. A caller writing one +``except ZarrClientError`` around the client would therefore miss every entity +failure -- so the boundary translates once, here, rather than each method +wrapping its own body. +""" + +from __future__ import annotations + +from typing import NoReturn + +from ..dclimate_zarr_errors import ( + DatasetCorruptError, + InvalidSelectionError, + NoDataFoundError, +) + + +def translate_entity_error(cause: BaseException) -> NoReturn: + """Re-raise an entity query failure as this library's own error type. + + The mapping follows the distinction the rest of this library draws, by who + has to act: a malformed request is an :class:`InvalidSelectionError` (the + caller's to fix), a well-formed request that matched nothing is a + :class:`NoDataFoundError` (an empty answer, nobody's fault), and bytes that + do not describe a readable dataset are a :class:`DatasetCorruptError` (the + publisher's). ``tabular_py`` marks the first two on the error itself, so this + reads a field rather than matching on message text, which would break the + first time a message improved. + + Transport failures are deliberately left untranslated, because they are none + of those three: a gateway timeout is retryable and says nothing about the + dataset. + + The original message is preserved verbatim: it is the only part that names + the entity, column, or distance that actually failed. + """ + # Imported here, not at module scope, so that importing this module -- which + # the package's error exports do -- does not pull in tabular_py and, through + # it, pyarrow, on every `import dclimate_client_py`. + from tabular_py.errors import ( + DatasetIntegrityError, + DatasetReaderError, + DclimateTabularError, + PredicateError, + RangeSourceError, + EntitySelectionError, + ) + + if isinstance(cause, EntitySelectionError): + if cause.reason == "not-found": + raise NoDataFoundError(str(cause)) from cause + raise InvalidSelectionError(str(cause)) from cause + + # Corrupt data is not a bad question. Checked as its own branch rather than + # before the reader case for emphasis: tabular deliberately does not descend + # `DatasetIntegrityError` from `DatasetReaderError`, precisely so a boundary + # like this one cannot sweep it into "you asked wrong". + if isinstance(cause, DatasetIntegrityError): + raise DatasetCorruptError(str(cause)) from cause + + # Other reader failures are malformed requests too -- an unknown column, a + # predicate against a column that is not comparable, an inverted bounding + # box or a polygon with no outer ring. The geo case arrives here as a + # `GeoFilterError`, which tabular >= 0.2.1 descends from + # `DatasetReaderError`; the floor in `pyproject.toml` is what makes naming + # it separately unnecessary, since before that it was rooted at the base + # class and reached the corruption branch below instead. + if isinstance(cause, (DatasetReaderError, PredicateError)): + raise InvalidSelectionError(str(cause)) from cause + + # The gateway failing to hand over bytes is a transport fact, not a statement + # about the dataset: it is retryable, and reporting it as corruption would + # send a caller to the publisher over what is usually a network blip. Checked + # before the base class below, which it descends from. + if isinstance(cause, RangeSourceError): + raise cause + + # Any remaining tabular error means bytes arrived and did not describe a + # readable dataset -- a CID naming a UnixFS file rather than a root (a + # `CodecError` from the dag-cbor decode), or a well-formed block whose fields + # are not a dataset root (a `WireError`). Both are corruption in the same + # sense as `DatasetIntegrityError`, and no rephrasing fixes either. + # + # Matched on the base class rather than by listing `CodecError` and + # `WireError`: this is the branch that keeps the promise that everything + # escaping the client is a `ZarrClientError`, and a list of leaf types + # silently stops keeping it the day tabular adds one. The specific class + # stays visible in the message, which is preserved verbatim. + if isinstance(cause, DclimateTabularError): + raise DatasetCorruptError(f"{type(cause).__name__}: {cause}") from cause + + # Anything else is not tabular's and not ours to reinterpret: a TypeError + # from a bug in this client, or an HTTP failure that never reached the + # reader, should surface as itself. + raise cause diff --git a/dclimate_client_py/entities/wrap.py b/dclimate_client_py/entities/wrap.py new file mode 100644 index 0000000..5f0e6fe --- /dev/null +++ b/dclimate_client_py/entities/wrap.py @@ -0,0 +1,104 @@ +"""Keeping the error boundary closed across a whole selection chain. + +Mirrors ``dclimate-client-js`` ``src/entities/wrap.ts``, which uses a ``Proxy`` +for the same reason this uses ``__getattr__`` delegation. + +Translating only at ``load`` leaves a hole the size of the actual API. ``open`` +parses a manifest; the errors a caller is far likelier to hit come later, from +``select`` on an unknown entity, ``where`` on a non-comparable column, or +``rows`` on a selection that matched nothing. Those are raised inside +``tabular_py`` and, untranslated, escape as ``DatasetReaderError`` -- so the one +``except ZarrClientError`` this library tells people to write misses precisely +the failures they were most likely to be catching for. + +Delegation rather than a hand-written class of forwarding methods, for two +reasons. Selections return *new* ``EntityDataset`` instances, so a class would +have to remember to re-wrap the result of every chainable -- and a method added +to ``tabular_py`` later would silently return an unwrapped dataset, reopening the +hole halfway down a chain. And ``plan``/``rows``/``to_arrow`` return plain data +that must pass through untouched; delegation distinguishes those by what comes +back rather than by a list someone has to keep current. + +Three return shapes are handled, because the API has all three: + +* sync chainable (``select``, ``time_range``, ``where``, ``circle``) -> re-wrap +* async chainable (``nearest``) -> re-wrap on await +* async terminal (``rows``, ``plan``, ``list_entities``) -> translate the raise +""" + +from __future__ import annotations + +import functools +import inspect +from typing import TYPE_CHECKING, Any + +from .errors import translate_entity_error + +if TYPE_CHECKING: # pragma: no cover + from tabular_py import EntityDataset + + +class WrappedEntityDataset: + """A :class:`~tabular_py.EntityDataset` whose every failure is this library's. + + Attribute access is forwarded, so this stays correct as ``tabular_py`` grows + methods. Anything callable is wrapped; anything else (a property such as + ``reader`` or ``query_spec``) passes straight through. + """ + + __slots__ = ("_dataset",) + + def __init__(self, dataset: EntityDataset) -> None: + object.__setattr__(self, "_dataset", dataset) + + @property + def unwrapped(self) -> EntityDataset: + """The underlying dataset, for callers who want tabular's own errors.""" + return self._dataset # type: ignore[attr-defined,no-any-return] + + def __getattr__(self, name: str) -> Any: + # Only reached for names not found on this class, which is every method + # of the wrapped dataset. + attribute = getattr(object.__getattribute__(self, "_dataset"), name) + if not callable(attribute): + return attribute + + @functools.wraps(attribute) + def call(*args: Any, **kwargs: Any) -> Any: + try: + result = attribute(*args, **kwargs) + except BaseException as cause: + # A synchronous raise -- an unknown column rejected at selection + # time, before any I/O. + translate_entity_error(cause) + if inspect.isawaitable(result): + return _awaited(result) + return _rewrap(result) + + return call + + def __repr__(self) -> str: + return f"{type(self).__name__}({self._dataset!r})" # type: ignore[attr-defined] + + +async def _awaited(awaitable: Any) -> Any: + try: + resolved = await awaitable + except BaseException as cause: + translate_entity_error(cause) + # `nearest` resolves to a further dataset; keep the chain wrapped. + return _rewrap(resolved) + + +def _rewrap(value: Any) -> Any: + """Re-wrap a returned dataset, so translation does not stop at the first link.""" + from tabular_py import EntityDataset + + if isinstance(value, EntityDataset): + return WrappedEntityDataset(value) + return value + + +def wrap_entity_dataset(dataset: EntityDataset) -> WrappedEntityDataset: + """Wrap a dataset so every method failure comes back as a ``ZarrClientError``.""" + return WrappedEntityDataset(dataset) diff --git a/dclimate_client_py/stac_catalog.py b/dclimate_client_py/stac_catalog.py index 0691b6a..970cfa2 100644 --- a/dclimate_client_py/stac_catalog.py +++ b/dclimate_client_py/stac_catalog.py @@ -485,6 +485,7 @@ def resolve_dataset_from_stac( return ResolvedDatasetDetails( cid=href, variant=selected_variant, + layout=properties.get("dclimate:layout"), versions_api=properties.get("dclimate:versions_api"), provenance_api=properties.get("dclimate:provenance_api"), citation_api=properties.get("dclimate:citation_api"), diff --git a/dclimate_client_py/stac_server.py b/dclimate_client_py/stac_server.py index b09d9a4..676925a 100644 --- a/dclimate_client_py/stac_server.py +++ b/dclimate_client_py/stac_server.py @@ -100,6 +100,12 @@ class ResolvedDatasetDetails: cid: str variant: str + #: Storage layout the item advertises: ``"tabular"`` for entity + #: (point-observation) datasets, ``"zarr"`` or absent for the gridded + #: datasets that were the only kind when this type was written. This is what + #: lets ``load_entities`` refuse a gridded collection rather than handing its + #: CID to a reader that will fail deep inside a manifest parse. + layout: Optional[str] = None versions_api: Optional[str] = None provenance_api: Optional[str] = None citation_api: Optional[str] = None @@ -109,6 +115,14 @@ class ResolvedDatasetDetails: is_citable: Optional[bool] = None retention_class: Optional[str] = None zarr_resolutions: tuple[ZarrResolution, ...] = () + #: The collection id this resolution actually landed on, when it differs + #: from the one the caller asked for. Resolution may expand a unique short + #: name (``ghcnd`` -> ``noaa_ghcnd``), and that expanded identity is what + #: the item was found under -- so callers building metadata must report it + #: rather than the name they started with, which would name a collection + #: the result did not come from. ``None`` means no expansion happened and + #: the requested name stands. + collection: Optional[str] = None def as_resolved_dataset(self) -> ResolvedDataset: return ResolvedDataset(self.cid, self.variant) @@ -525,6 +539,7 @@ def _effective_variant(feature: Dict[str, Any]) -> str: return ResolvedDatasetDetails( cid=cid, variant=selected_variant, + layout=properties.get("dclimate:layout"), versions_api=properties.get("dclimate:versions_api"), provenance_api=properties.get("dclimate:provenance_api"), citation_api=properties.get("dclimate:citation_api"), @@ -660,6 +675,97 @@ def _strip_ipfs_scheme(cid: Optional[str]) -> Optional[str]: return cid.replace("ipfs://", "", 1) if cid.startswith("ipfs://") else cid +def _fetch_all_collections(server_url: str) -> list[Dict[str, Any]]: + """ + Fetch every page of ``/collections``. + + The endpoint paginates and defaults to a page size smaller than the number + of collections published, so a single unpaged request silently returns a + prefix: ``numberMatched`` exceeds ``numberReturned`` and the tail is simply + absent. That is invisible at the call site -- the response is a well-formed + list, just a short one -- and the collections it drops lose the title and + organization this endpoint is the only source of. + + Follows ``rel="next"`` rather than passing a large ``limit``, because a + limit only moves the cliff: it is a guess about how many collections will + exist later, and the day the catalogue outgrows it the truncation returns + silently. The link is what the server itself says comes next. + + Shares the page cap, repeat-detection, and origin check of the item search + above: a server returning a ``next`` that points at the page just fetched + would otherwise spin forever, and one pointing off-origin is refused rather + than followed. Every one of those ends the walk by raising, because each + leaves the catalogue incomplete -- and an incomplete catalogue that returns + normally is indistinguishable from a complete one. + """ + collections: list[Dict[str, Any]] = [] + seen: set[str] = set() + url: Optional[str] = f"{server_url.rstrip('/')}/collections" + + for _ in range(_MAX_SEARCH_PAGES): + if not url: + break + if url in seen: + raise ValueError( + "STAC server /collections pagination repeated a request; " + "results truncated" + ) + seen.add(url) + + response = _client().get(url, timeout=10) + response.raise_for_status() + body = response.json() + collections.extend(body.get("collections", []) or []) + + next_href = next( + ( + link.get("href") + for link in (body.get("links") or []) + if isinstance(link, dict) and link.get("rel") == "next" + ), + None, + ) + if not next_href: + # Cleared before breaking so a surviving `url` below means exactly + # one thing: the page budget ran out with another page still to + # fetch. A clean finish must not look like a truncated one. + url = None + break + + # Resolved against the current page so a relative `next` works. + candidate = urljoin(url, next_href) + parsed_candidate = urlsplit(candidate) + # Following an off-origin link would be an open redirect out to another + # host, so it is refused -- but refused loudly. Dropping it silently + # would end the walk exactly like a server that said it was finished, + # handing back a catalogue that looks complete while the collections + # past this point go missing. Same rule, and same reason, as the item + # search's pagination-link check. + if ( + _url_origin(candidate) != _url_origin(server_url) + or parsed_candidate.username is not None + or parsed_candidate.password is not None + ): + raise ValueError( + "STAC server /collections pagination link must use the " + f"configured server origin {_url_origin(server_url)!r}: " + f"{candidate!r}" + ) + url = candidate + + # Reached only with a live `next` still in hand: the loop ran out of budget + # rather than out of pages. Returning here would hand back a catalogue that + # looks complete, and the collections missing from it would surface later as + # untitled or unknown datasets rather than as this failure. + if url: + raise ValueError( + f"STAC server /collections pagination exceeded {_MAX_SEARCH_PAGES} " + "pages; results truncated" + ) + + return collections + + def list_available_datasets_from_stac_server( server_url: str = STAC_SERVER_URL, ) -> Dict[str, Dict[str, Any]]: @@ -687,9 +793,7 @@ def list_available_datasets_from_stac_server( disagree. - Search pagination is bounded to avoid looping on malformed ``next`` links. """ - collections_resp = _client().get(f"{server_url}/collections", timeout=10) - collections_resp.raise_for_status() - collections_body = collections_resp.json() + collections_body = {"collections": _fetch_all_collections(server_url)} # Accumulator per collection. Built up from /collections then enriched by # the /search response. Collections that have no items end up filtered out diff --git a/pyproject.toml b/pyproject.toml index 53385ce..b5b524c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,6 +39,7 @@ dependencies = [ "numcodecs[crc32c]>=0.14,<0.16", "numpy>=2.1.3", "py_hamt>=3.6.0", + "dclimate-tabular-py>=0.2.1", "multiformats>=0.3.1", "geopandas>=1.0.0", "pandas>=2.2.0", diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py new file mode 100644 index 0000000..0babc56 --- /dev/null +++ b/tests/helpers/__init__.py @@ -0,0 +1 @@ +"""Test fixtures shared across this suite.""" diff --git a/tests/helpers/entity_fixture.py b/tests/helpers/entity_fixture.py new file mode 100644 index 0000000..80eab03 --- /dev/null +++ b/tests/helpers/entity_fixture.py @@ -0,0 +1,241 @@ +"""A tiny real `dclimate-tabular/1` dataset, built in memory. + +Mirrors ``dclimate-client-js`` ``tests/entities-columnkey.test.ts``, which builds +its fixture with tabular's ``DatasetWriter``. ``tabular_py`` is deliberately +reader-only and ships no writer, so this composes the same public encoders the +reader exposes -- ``*_to_wire``, ``make_block``, ``MemoryRangeSource`` -- into +the smallest dataset that can answer a query. + +Deliberately not a writer: one entity, one fragment, no bucketing, compaction, +rollup, or commit sequencing. What it exists to support is the ``column_key`` +contract, which needs a dataset whose *stored* field name differs from its +*published* column name -- GHCND's ``tmax``/``TMAX`` -- read end to end through +the real reader rather than a stand-in. + +Every figure in the manifest is derived by reading the Parquet bytes back, so +the manifest cannot describe a payload it does not have. +""" + +from __future__ import annotations + +import io +from typing import Any + +import pyarrow as pa +import pyarrow.parquet as pq +from tabular_py import ( + MemoryRangeSource, + blake3_digest, + entity_entry_to_wire, + make_block, + root_to_wire, + table_schema_to_wire, +) + +# The structural types live in `tabular_py.model`; only part of the model is +# re-exported from the barrel, and reaching for the module directly keeps this +# working whichever names the barrel happens to carry. +from tabular_py.model import ( + FLAG_SORTED, + SPEC_VERSION, + ColumnChunk, + ColumnStat, + DatasetRoot, + DatasetStats, + EntityEntry, + EntityIndexInline, + EntitySummary, + FragmentBucket, + FragmentEntry, + GeoPoint, + Latest, + Partitioning, + RowGroup, + TableField, + TableSchema, + WriteConfig, +) + +DAY_US = 24 * 60 * 60 * 1_000_000 +# 2024-01-01T00:00:00Z, in microseconds. +EPOCH_2024 = 1_704_067_200 * 1_000_000 + +ENTITY_ID = "USW00094728" +ROW_COUNT = 3 +LAT_MICRO = 40_779_000 +LON_MICRO = -73_969_000 + +# Stored lowercase, exactly as GHCND stores it -- so a caller asking for the +# published `TMAX` needs the mapping, which is the whole point of the fixture. +SCHEMA = TableSchema( + schema_id=0, + fields=( + TableField(field_id=1, name="entity_id", type="string", nullable=False), + TableField(field_id=2, name="ts", type="int64", nullable=False), + TableField( + field_id=10, name="tmax", type="int32", nullable=True, units="degC_tenths" + ), + ), +) + +_TIMESTAMPS = [EPOCH_2024 + day * DAY_US for day in range(ROW_COUNT)] +_TMAX = [250 + day for day in range(ROW_COUNT)] + + +def _parquet_bytes() -> bytes: + table = pa.table( + { + "entity_id": [ENTITY_ID] * ROW_COUNT, + "ts": _TIMESTAMPS, + "tmax": _TMAX, + }, + schema=pa.schema( + [ + pa.field("entity_id", pa.string(), nullable=False), + pa.field("ts", pa.int64(), nullable=False), + pa.field("tmax", pa.int32(), nullable=True), + ] + ), + ) + buffer = io.BytesIO() + pq.write_table(table, buffer, compression="zstd", version="2.6") + return buffer.getvalue() + + +def _fragment_entry(data: bytes, cid: Any) -> FragmentEntry: + """Describe the fragment by reading it back, never by asserting its shape.""" + metadata = pq.ParquetFile(io.BytesIO(data)).metadata + # A Parquet file ends with the footer, its 4-byte length, and `PAR1`. + footer_length = int.from_bytes(data[-8:-4], "little") + footer_offset = len(data) - 8 - footer_length + footer = data[footer_offset : footer_offset + footer_length] + + field_ids = [field.field_id for field in SCHEMA.fields] + row_groups: list[RowGroup] = [] + stats: dict[int, tuple[int, Any, Any]] = {} + first_row = 0 + + for group_index in range(metadata.num_row_groups): + group = metadata.row_group(group_index) + chunks: list[ColumnChunk] = [] + for column_index in range(group.num_columns): + column = group.column(column_index) + field_id = field_ids[column_index] + start = column.dictionary_page_offset or column.data_page_offset + chunks.append( + ColumnChunk( + field_id=field_id, + offset=int(start), + length=int(column.total_compressed_size), + ) + ) + null_count, minimum, maximum = stats.get(field_id, (0, None, None)) + column_stats = column.statistics + if column_stats is not None: + null_count += int(column_stats.null_count) + low, high = column_stats.min, column_stats.max + minimum = low if minimum is None else min(minimum, low) + maximum = high if maximum is None else max(maximum, high) + stats[field_id] = (null_count, minimum, maximum) + + row_groups.append( + RowGroup( + first_row=first_row, + row_count=group.num_rows, + ts_min=min(_TIMESTAMPS), + ts_max=max(_TIMESTAMPS), + chunks=tuple(chunks), + ) + ) + first_row += group.num_rows + + return FragmentEntry( + cid=cid, + byte_length=len(data), + schema_id=SCHEMA.schema_id, + tier=0, + flags=FLAG_SORTED, + row_count=ROW_COUNT, + ts_min=min(_TIMESTAMPS), + ts_max=max(_TIMESTAMPS), + footer_offset=footer_offset, + footer_length=footer_length, + footer_digest=blake3_digest(footer), + col_stats=tuple( + ColumnStat(field_id=field_id, null_count=null, min=low, max=high) + for field_id, (null, low, high) in sorted(stats.items()) + ), + row_groups=tuple(row_groups), + commit_seq=0, + ) + + +def build_dataset() -> tuple[MemoryRangeSource, str]: + """A one-entity dataset, and the root CID to open it by.""" + blocks: dict[str, bytes] = {} + + def put(value: Any) -> Any: + cid, encoded = make_block(value) + blocks[str(cid)] = encoded + return cid + + data = _parquet_bytes() + fragment_cid, _ = make_block(data) + # Parquet bytes are stored raw, not dag-cbor wrapped: the reader fetches + # byte ranges out of them directly. + blocks[str(fragment_cid)] = data + + schema_cid = put(table_schema_to_wire(SCHEMA)) + fragment = _fragment_entry(data, fragment_cid) + + entry = EntityEntry( + entity_id=ENTITY_ID, + geo=GeoPoint(lat_micro=LAT_MICRO, lon_micro=LON_MICRO), + elev_cm=0, + ts_min=min(_TIMESTAMPS), + ts_max=max(_TIMESTAMPS), + row_count=ROW_COUNT, + columns=("tmax",), + latest=Latest(ts=max(_TIMESTAMPS), fragment_idx=0), + fragments=(fragment,), + ) + entry_cid = put(entity_entry_to_wire(entry)) + + summary = EntitySummary( + entity_id=ENTITY_ID, + ts_min=min(_TIMESTAMPS), + ts_max=max(_TIMESTAMPS), + lat_micro=LAT_MICRO, + lon_micro=LON_MICRO, + entry=entry_cid, + gaps=(), + ) + + root = DatasetRoot( + spec=SPEC_VERSION, + dataset_id="columnkey-e2e", + sequence=0, + created_us=EPOCH_2024, + message="fixture", + watermark_us=max(_TIMESTAMPS), + parent=None, + ancestry=(), + schemas=(schema_cid,), + current_schema=SCHEMA.schema_id, + partitioning=Partitioning(key=("entity_id",), sort=("ts",)), + write_config=WriteConfig( + fragment_bucket=FragmentBucket(unit="year", count=1), delta_ts=False + ), + entities=EntityIndexInline(entries=(summary,)), + projections={}, + compat=(), + stats=DatasetStats( + entities=1, + rows=ROW_COUNT, + ts_min=min(_TIMESTAMPS), + ts_max=max(_TIMESTAMPS), + ), + prev_hash_compat=None, + ) + root_cid = put(root_to_wire(root)) + return MemoryRangeSource(blocks), str(root_cid) diff --git a/tests/test_entities.py b/tests/test_entities.py new file mode 100644 index 0000000..0b64407 --- /dev/null +++ b/tests/test_entities.py @@ -0,0 +1,508 @@ +"""Entity dataset support: the client namespace and the error boundary. + +Mirrors ``dclimate-client-js`` ``tests/entities.test.ts``, +``tests/entities-wrap.test.ts``, and ``tests/entities-columnkey.test.ts``. + +What is under test is the translation boundary, not ``tabular_py``'s reader: +these tests need methods that fail on demand, in each shape the real class can +fail in, so the datasets here are stand-ins rather than real ones opened over a +gateway. +""" + +from __future__ import annotations + +import pytest + +from dclimate_client_py.dclimate_zarr_errors import ( + DatasetCorruptError, + DatasetNotFoundError, + InvalidSelectionError, + NoDataFoundError, + TabularNotInstalledError, + ZarrClientError, +) +from dclimate_client_py.dclimate_client import dClimateClient +from dclimate_client_py.entities import EntitiesClient + +tabular_py = pytest.importorskip( + "tabular_py", + reason="entity support needs the dclimate-tabular-py distribution", +) + +from tabular_py.errors import ( # noqa: E402 + CodecError, + DatasetIntegrityError, + DatasetReaderError, + GeoFilterError, + PredicateError, + RangeSourceError, + EntitySelectionError, + WireError, +) + +from dclimate_client_py.entities.errors import translate_entity_error # noqa: E402 +from dclimate_client_py.entities.wrap import wrap_entity_dataset # noqa: E402 + + +def fake(**overrides: object) -> tabular_py.EntityDataset: + """A stand-in for a real dataset. + + Built by hand rather than opened over a gateway: what is under test is the + boundary, so these need methods that fail on demand. It is a real + ``EntityDataset`` instance so the wrapper's ``isinstance`` re-wrapping check + sees what it would see in production. + """ + dataset = object.__new__(tabular_py.EntityDataset) + for name, value in overrides.items(): + object.__setattr__(dataset, name, value) + return dataset + + +class TestClientNamespace: + def test_available_without_configuration(self) -> None: + # Siren needs credentials and raises when unconfigured; entity reads + # only need the transport the client already has, so requiring an option + # would be ceremony with nothing behind it. + client = dClimateClient() + assert isinstance(client.entities, EntitiesClient) + + def test_reuses_one_instance_across_accesses(self) -> None: + client = dClimateClient() + assert client.entities is client.entities + + async def test_rejects_a_malformed_cid_before_touching_the_network(self) -> None: + calls: list[str] = [] + + class Recording: + async def get_block(self, cid: object) -> bytes: + calls.append("get_block") + raise AssertionError("should not be reached") + + async def get_range(self, cid: object, offset: int, length: int) -> bytes: + calls.append("get_range") + raise AssertionError("should not be reached") + + entities = EntitiesClient(gateway_url="http://127.0.0.1:8080") + entities._source = lambda _gateway: Recording() # type: ignore[method-assign] + + with pytest.raises(DatasetNotFoundError): + await entities.load("obviously-not-a-cid") + # The point of the assertion: a typo'd CID should fail locally and + # instantly, not after a gateway round trip. + assert calls == [] + + async def test_requires_a_cid_until_catalog_resolution_exists(self) -> None: + client = dClimateClient() + with pytest.raises(DatasetNotFoundError): + await client.entities.load("") + + async def test_routes_reads_through_the_gateway_it_was_given(self) -> None: + entities = EntitiesClient(gateway_url="https://gateway.example") + source = entities._source(None) + assert isinstance(source, tabular_py.GatewayRangeSource) + # A 404 would end the load; the assertion is about where reads go. + assert "gateway.example" in repr(source.__dict__) + await entities.aclose() + + async def test_a_per_request_gateway_overrides_the_client_default(self) -> None: + entities = EntitiesClient(gateway_url="https://default.example") + source = entities._source("https://override.example") + assert "override.example" in repr(source.__dict__) + await entities.aclose() + + def test_prefers_the_clients_own_cas_when_open(self) -> None: + sentinel = object() + entities = EntitiesClient(gateway_url="https://unused.example", cas=sentinel) + source = entities._source(None) + # Reads go through the client's configured transport -- pinning, retries + # and endpoints included -- rather than a second HTTP path. + assert isinstance(source, tabular_py.CasRangeSource) + + def test_a_gateway_override_bypasses_the_cas(self) -> None: + entities = EntitiesClient(gateway_url="https://default.example", cas=object()) + source = entities._source("https://override.example") + assert isinstance(source, tabular_py.GatewayRangeSource) + + +class FakeCas: + """Stands in for a ``KuboCAS`` the client owns and closes on exit.""" + + async def __aexit__(self, *exc: object) -> None: + return None + + +class TestNamespaceLifecycle: + """Who owns which transport, and when it stops being usable.""" + + async def test_a_closed_context_does_not_leave_a_dead_transport_cached( + self, + ) -> None: + # A KuboCAS never reopens once closed. Keeping the instance built around + # one would make entity reads after the context fail on a dead + # transport, instead of falling back to the gateway as documented. + client = dClimateClient() + client._kubo_cas = FakeCas() # type: ignore[assignment] + during = client.entities + assert during._cas is client._kubo_cas + + await client.__aexit__(None, None, None) + + assert client._entities_client is None + after = client.entities + assert after is not during + assert after._cas is None + + async def test_rebuilding_onto_the_cas_does_not_strand_gateway_sources( + self, + ) -> None: + # Entity data loaded before __aenter__ opens a gateway source. The + # rebuilt instance is the only one __aexit__ closes, so the old one's + # sources have to come with it or their pools leak. + closed: list[object] = [] + + class Source: + async def aclose(self) -> None: + closed.append(self) + + client = dClimateClient() + before = client.entities + source = Source() + before._owned_sources.append(source) + + client._kubo_cas = FakeCas() # type: ignore[assignment] + after = client.entities + assert after is not before + assert before._owned_sources == [] + assert after._owned_sources == [source] + + await client.__aexit__(None, None, None) + assert closed == [source] + + async def test_repeated_gateway_reads_reuse_one_source(self) -> None: + # Each gateway source owns an httpx client, so opening one per call + # would make a long-lived client accumulate a connection pool per query + # until aclose. Reuse is keyed by URL: a per-request override is a + # different gateway and gets its own. + entities = EntitiesClient(gateway_url="https://gw.example") + + first = entities._source(None) + assert entities._source(None) is first + assert len(entities._owned_sources) == 1 + + override = entities._source("https://other.example") + assert override is not first + assert len(entities._owned_sources) == 2 + + await entities.aclose() + # A closed source must not be handed out again. + assert entities._owned_sources == [] + assert entities._source(None) is not first + + async def test_one_failing_source_does_not_strand_the_others(self) -> None: + # The list is cleared up front, so a source skipped here is never + # retried by anything. + closed: list[str] = [] + + class Source: + def __init__(self, name: str, fails: bool = False) -> None: + self.name = name + self.fails = fails + + async def aclose(self) -> None: + if self.fails: + raise RuntimeError(f"{self.name} refused to close") + closed.append(self.name) + + entities = EntitiesClient(gateway_url="https://unused.example") + entities._owned_sources.extend( + [Source("first"), Source("second", fails=True), Source("third")] + ) + + with pytest.raises(RuntimeError, match="second refused to close"): + await entities.aclose() + + # The failure is reported, but not at the cost of the healthy pools. + assert closed == ["first", "third"] + assert entities._owned_sources == [] + + +class TestTranslateEntityError: + """The mapping, by who has to act.""" + + def test_not_found_selection_becomes_no_data_found(self) -> None: + # A well-formed question with an empty answer stays an empty answer, + # rather than being reported as the caller's mistake. + with pytest.raises(NoDataFoundError): + translate_entity_error(EntitySelectionError("no match", "not-found")) + + def test_invalid_selection_becomes_invalid_selection(self) -> None: + with pytest.raises(InvalidSelectionError): + translate_entity_error(EntitySelectionError("bad", "invalid")) + + def test_integrity_failure_becomes_corrupt_not_invalid(self) -> None: + # tabular deliberately does not descend DatasetIntegrityError from + # DatasetReaderError precisely so this boundary cannot sweep a corrupt + # dataset into "you asked wrong". + with pytest.raises(DatasetCorruptError): + translate_entity_error(DatasetIntegrityError("bad digest")) + + @pytest.mark.parametrize( + "cause", + [ + DatasetReaderError("unknown column"), + PredicateError("not comparable"), + # A malformed geometry is the caller's to fix, exactly like a + # malformed predicate. Kept as its own case because nothing here + # names `GeoFilterError`: it is caught only by descending from + # `DatasetReaderError`, which it did not do before tabular 0.2.1. + # If that ever regresses upstream, this fails rather than silently + # blaming the publisher for an inverted bounding box. + GeoFilterError("bbox latitude bounds are inverted"), + ], + ) + def test_reader_and_predicate_failures_are_invalid_selections( + self, cause: Exception + ) -> None: + with pytest.raises(InvalidSelectionError): + translate_entity_error(cause) + + def test_transport_failures_pass_through_untranslated(self) -> None: + # A gateway timeout is retryable and says nothing about the dataset; + # reporting it as corruption would send a caller to the publisher over + # what is usually a network blip. + original = RangeSourceError("gateway 503") + with pytest.raises(RangeSourceError) as raised: + translate_entity_error(original) + assert raised.value is original + + @pytest.mark.parametrize( + "cause", [CodecError("not dag-cbor"), WireError("not a root")] + ) + def test_other_tabular_errors_are_corruption(self, cause: Exception) -> None: + # Bytes arrived and did not describe a readable dataset. Matched on the + # base class, so this keeps holding the day tabular adds a leaf type. + with pytest.raises(DatasetCorruptError) as raised: + translate_entity_error(cause) + # The specific class stays visible even though the branch is generic. + assert type(cause).__name__ in str(raised.value) + + def test_foreign_errors_surface_as_themselves(self) -> None: + # A TypeError from a bug in this client is not ours to reinterpret. + original = TypeError("bug") + with pytest.raises(TypeError) as raised: + translate_entity_error(original) + assert raised.value is original + + def test_message_is_preserved_verbatim(self) -> None: + # The message is the only part naming the entity, column, or distance + # that actually failed. + with pytest.raises(InvalidSelectionError, match="column 'TMPX' at row 12"): + translate_entity_error(DatasetReaderError("column 'TMPX' at row 12")) + + +class TestWrapEntityDataset: + """The boundary has to hold for the whole chain, not just ``load``.""" + + async def test_translates_a_rejection_from_a_terminal_method(self) -> None: + # The gap the wrapper exists to close: `rows()` is where a caller most + # often meets a reader error, and it is nowhere near `load`'s try/except. + async def rows() -> list[object]: + raise DatasetReaderError("unknown column") + + dataset = wrap_entity_dataset(fake(rows=rows)) + with pytest.raises(InvalidSelectionError): + await dataset.rows() + + async def test_keeps_the_not_found_distinction_across_the_boundary(self) -> None: + async def rows() -> list[object]: + raise EntitySelectionError("no match", "not-found") + + dataset = wrap_entity_dataset(fake(rows=rows)) + with pytest.raises(NoDataFoundError): + await dataset.rows() + + def test_translates_a_synchronous_raise_from_a_selector(self) -> None: + # An unknown column rejected at selection time, before any I/O. + def elements(*names: str) -> object: + raise DatasetReaderError("unknown element") + + dataset = wrap_entity_dataset(fake(elements=elements)) + with pytest.raises(InvalidSelectionError): + dataset.elements("TMPX") + + def test_rewraps_a_sync_chainable_so_translation_survives_the_chain(self) -> None: + async def rows() -> list[object]: + raise DatasetReaderError("late failure") + + inner = fake(rows=rows) + dataset = wrap_entity_dataset(fake(select=lambda *ids: inner)) + selected = dataset.select("USW00023174") + # Without re-wrapping, translation would stop at the first link and this + # would raise tabular's error instead of this library's. + assert type(selected).__name__ == "WrappedEntityDataset" + + async def test_rewraps_an_async_chainable(self) -> None: + async def rows() -> list[object]: + raise DatasetReaderError("late failure") + + inner = fake(rows=rows) + + async def nearest(*args: object, **kwargs: object) -> object: + return inner + + dataset = wrap_entity_dataset(fake(nearest=nearest)) + selected = await dataset.nearest(34.0, -118.0) + assert type(selected).__name__ == "WrappedEntityDataset" + with pytest.raises(InvalidSelectionError): + await selected.rows() + + async def test_passes_plain_data_through_untouched(self) -> None: + payload = [{"entity_id": "USW00023174", "value": 3}] + + async def rows() -> list[object]: + return payload + + dataset = wrap_entity_dataset(fake(rows=rows)) + assert await dataset.rows() is payload + + def test_non_callable_attributes_pass_through(self) -> None: + # `_query` backs the read-only `query_spec` property, so this covers the + # real shape: a plain attribute forwarded without being called. + dataset = wrap_entity_dataset(fake(_query="a-query")) + assert dataset._query == "a-query" + + def test_unwrapped_exposes_the_underlying_dataset(self) -> None: + inner = fake(_query="a-query") + assert wrap_entity_dataset(inner).unwrapped is inner + + async def test_every_escaping_error_is_this_librarys(self) -> None: + # The promise the boundary exists to keep: one `except ZarrClientError` + # around the client catches entity failures too. + for cause in ( + DatasetReaderError("bad"), + EntitySelectionError("gone", "not-found"), + DatasetIntegrityError("corrupt"), + WireError("not a root"), + ): + + async def rows(_cause: Exception = cause) -> list[object]: + raise _cause + + dataset = wrap_entity_dataset(fake(rows=rows)) + with pytest.raises(ZarrClientError): + await dataset.rows() + + +class TestMissingDependency: + def test_absence_names_the_distribution_not_the_module(self, monkeypatch) -> None: + import builtins + + from dclimate_client_py.entities import entities_client + + real_import = builtins.__import__ + + def missing(name: str, *args: object, **kwargs: object) -> object: + if name == "tabular_py": + raise ImportError("No module named 'tabular_py'") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", missing) + # The whole point of catching this: the import name and the distribution + # name differ, so the stock ModuleNotFoundError names `tabular_py`, which + # `pip install` cannot find. The message has to name the installable one. + with pytest.raises(TabularNotInstalledError, match="dclimate-tabular-py"): + entities_client._require_tabular() + + +class TestColumnKey: + """Naming, end to end through the real reader rather than a stand-in. + + Mirrors ``dclimate-client-js`` ``tests/entities-columnkey.test.ts``, with one + deliberate difference in what is asserted. A dataset's published column names + are a property of its profile, not of the stored blocks: every dClimate + dataset published so far stores lowercase field names (``tmax``) and + publishes the canonical uppercase element (``TMAX``). + + JS defaults to the identity, so *its* loader had to forward a `columnKey` + before any documented `TMAX` query worked. ``tabular_py.default_column_key`` + already uppercases, so the documented names work here with no mapping at all + -- verified against the published GHCND, NDBC, SCAN and SNOTEL roots, all + four of which store lowercase. + + What `column_key` buys this client is therefore the *other* direction: a + dataset whose published names are not simply the uppercase of its stored + ones -- NDBC's mixed-case `SwH`, say -- is unreachable without it, and the + parameter is what keeps such a dataset loadable at all. + """ + + @staticmethod + def _client() -> EntitiesClient: + return EntitiesClient(gateway_url="http://gateway.invalid") + + async def _load(self, **kwargs: object) -> object: + """Open the in-memory fixture through the real client boundary.""" + from tests.helpers.entity_fixture import build_dataset + + source, root = build_dataset() + entities = self._client() + # The transport is the one thing that cannot be in-memory end to end: + # substituting the source is what keeps this offline while every other + # layer -- CID parse, open, wrap, translate -- is the real one. + entities._source = lambda _gateway: source # type: ignore[method-assign] + return await entities.load(root, **kwargs) # type: ignore[arg-type] + + async def test_published_names_resolve_without_a_mapping(self) -> None: + # The fixture stores `tmax`, exactly as GHCND does. The reader's default + # uppercases, so the documented name works with no mapping -- this is the + # assertion that would fail if that default ever became the identity. + dataset = await self._load() + assert [(c.name, c.units) for c in dataset.columns()] == [ + ("TMAX", "degC_tenths") + ] + + records = await dataset.select("USW00094728").to_records("TMAX") + assert [record["value"] for record in records] == [250, 251, 252] + + async def test_a_mapping_is_forwarded_to_the_reader(self) -> None: + # The regression this parameter exists for: a dataset whose published + # names are not the uppercase of its stored ones is only reachable if the + # client actually forwards the mapping rather than dropping it. + dataset = await self._load(column_key=lambda field: field.name) + assert [c.name for c in dataset.columns()] == ["tmax"] + + records = await dataset.select("USW00094728").to_records("tmax") + assert [record["value"] for record in records] == [250, 251, 252] + + async def test_a_name_outside_the_mapping_is_an_invalid_selection(self) -> None: + # Under an identity mapping `TMAX` names nothing. It has to come back as + # this library's error, not tabular's, wherever it is raised -- eagerly at + # selection or lazily at read. + dataset = await self._load(column_key=lambda field: field.name) + with pytest.raises(InvalidSelectionError): + await dataset.elements("TMAX").rows() + + async def test_units_are_reported_but_never_applied(self) -> None: + # `degC_tenths` documents that 250 means 25.0 degrees. Scaling it here is + # how a reader ends up off by a power of ten, so the raw value stands. + dataset = await self._load() + assert dataset.columns()[0].units == "degC_tenths" + records = await dataset.select("USW00094728").to_records("TMAX") + assert records[0]["value"] == 250 + + @pytest.mark.parametrize(("lat", "lon"), [(100.0, 0.0), (40.78, 250.0)]) + async def test_out_of_range_coordinates_are_invalid_selections( + self, lat: float, lon: float + ) -> None: + # The validation lives in tabular; the client deliberately delegates it + # and translates at the boundary rather than duplicating bounds checks. + # This pins that contract from the caller's side: an impossible latitude + # must surface as this library's error, not as a plausible-looking entity + # for a point that does not exist. + dataset = await self._load() + with pytest.raises(InvalidSelectionError): + await dataset.find_nearest_entity(lat, lon) + + async def test_an_in_range_point_still_resolves(self) -> None: + dataset = await self._load() + nearest = await dataset.find_nearest_entity(40.78, -73.97) + assert nearest.entity_id == "USW00094728" diff --git a/tests/test_load_entities.py b/tests/test_load_entities.py new file mode 100644 index 0000000..c2df2a6 --- /dev/null +++ b/tests/test_load_entities.py @@ -0,0 +1,192 @@ +"""``client.load_entities``: catalog resolution for entity datasets. + +Mirrors ``dclimate-client-js`` ``tests/load-entities.test.ts``. + +What is under test is the dispatch this method adds -- the layout guard, the +``column_key`` default, and the metadata it assembles -- not STAC resolution, +which ``test_stac_server.py`` already covers against the live server. So +``_resolve_dataset_details`` is stubbed rather than the network. +""" + +from __future__ import annotations + +from typing import Any, Optional + +import pytest + +from dclimate_client_py.dclimate_client import dClimateClient +from dclimate_client_py.dclimate_zarr_errors import DatasetNotFoundError +from dclimate_client_py.stac_server import ResolvedDatasetDetails + + +def _resolved(**over: Any) -> ResolvedDatasetDetails: + fields: dict[str, Any] = { + "cid": "bafyr4ieoihgvnl5rvu6eh2fqduapjtz7wjp3e7kdtfxjospmavi5lgkoq4", + "variant": "default", + "layout": "tabular", + "commit_id": "k1commit", + "stream_id": "kjstream", + "version_label": "2026-08-26", + } + fields.update(over) + return ResolvedDatasetDetails(**fields) + + +class _Field: + def __init__(self, name: str) -> None: + self.name = name + + +def _stub( + monkeypatch: pytest.MonkeyPatch, + client: dClimateClient, + resolved: Optional[ResolvedDatasetDetails] = None, +) -> dict[str, Any]: + """Stub resolution and capture what reaches ``entities.load``.""" + captured: dict[str, Any] = {} + + async def fake_resolve(**_kwargs: Any) -> ResolvedDatasetDetails: + return resolved if resolved is not None else _resolved() + + async def fake_load(cid: str, **kwargs: Any) -> object: + captured["cid"] = cid + captured.update(kwargs) + captured["called"] = True + return object() + + monkeypatch.setattr(client, "_resolve_dataset_details", fake_resolve) + + class _Entities: + load = staticmethod(fake_load) + + monkeypatch.setattr(type(client), "entities", property(lambda _self: _Entities())) + return captured + + +@pytest.mark.asyncio +async def test_refuses_a_gridded_dataset(monkeypatch: pytest.MonkeyPatch) -> None: + """A Zarr CID opened as an entity dataset dies inside a manifest parse. + + That reads as corruption and sends the caller to the publisher rather than + to their own call, so the layout is checked before the reader sees it. + """ + client = dClimateClient() + captured = _stub(monkeypatch, client, _resolved(layout="zarr")) + + with pytest.raises(DatasetNotFoundError, match="not an entity dataset"): + await client.load_entities( + collection="ecmwf_era5", dataset="precipitation_total" + ) + assert "called" not in captured + + +@pytest.mark.asyncio +async def test_refuses_an_item_with_no_layout( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Absence is not permission. + + Entity support postdates ``dclimate:layout``, so an item without the field + is a gridded one from before the convention -- there is no such thing as a + legacy entity dataset to accommodate. + """ + client = dClimateClient() + captured = _stub(monkeypatch, client, _resolved(layout=None)) + + with pytest.raises(DatasetNotFoundError, match="'gridded' dataset"): + await client.load_entities(collection="ecmwf_era5", dataset="reanalysis") + assert "called" not in captured + + +@pytest.mark.asyncio +async def test_supplies_no_column_key_of_its_own( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """``column_key`` renames columns; it does not gate access to them. + + Without one every column is still readable under the schema's own field + names, which are what the dataset stores and so are never wrong. A default + here would be a guess at a dataset's publishing profile -- right for GHCND, + silently wrong for a profile like NDBC's ``.spec`` feed that publishes + ``SwH``. + """ + client = dClimateClient() + captured = _stub(monkeypatch, client) + + await client.load_entities(collection="noaa_ghcnd", dataset="station_observations") + assert "column_key" not in captured + + +@pytest.mark.asyncio +async def test_forwards_a_callers_column_key( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """NDBC preserves mixed case like ``SwH``, so a caller must be able to say + so explicitly.""" + client = dClimateClient() + captured = _stub(monkeypatch, client) + + await client.load_entities( + collection="noaa_ndbc", + dataset="buoy_observations", + column_key=lambda field: field.name, + ) + assert captured["column_key"](_Field("SwH")) == "SwH" + + +@pytest.mark.asyncio +async def test_returns_snapshot_identity(monkeypatch: pytest.MonkeyPatch) -> None: + """A settlement or citation has to say which snapshot it ran against, not + just "whatever was newest that day".""" + client = dClimateClient() + _stub(monkeypatch, client) + + _dataset, metadata = await client.load_entities( + collection="noaa_ghcnd", dataset="station_observations" + ) + + assert metadata["collection"] == "noaa_ghcnd" + assert metadata["dataset"] == "station_observations" + assert metadata["variant"] == "default" + assert metadata["organization"] == "noaa" + assert metadata["source"] == "stac" + assert metadata["commit_id"] == "k1commit" + assert metadata["stream_id"] == "kjstream" + assert metadata["version_label"] == "2026-08-26" + assert metadata["slug"] == "noaa_ghcnd/station_observations/default" + + +@pytest.mark.asyncio +async def test_passes_gateway_through(monkeypatch: pytest.MonkeyPatch) -> None: + client = dClimateClient() + captured = _stub(monkeypatch, client) + + await client.load_entities( + collection="noaa_ghcnd", + dataset="station_observations", + gateway_url="https://override.example", + ) + assert captured["gateway_url"] == "https://override.example" + + +@pytest.mark.asyncio +async def test_metadata_reports_the_collection_resolution_landed_on( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A short name expanded during resolution is what metadata reports. + + Resolution matches a unique short name against the catalogue (``ghcnd`` -> + ``noaa_ghcnd``). Reporting the requested name instead would not just + mislabel ``collection``: ``organization`` is derived by splitting it on + ``_``, so the unexpanded name yields no organization at all, and ``slug`` + -- which names the returned dataset -- points at a collection the data did + not come from. + """ + client = dClimateClient(stac_server_url=None) + _stub(monkeypatch, client, _resolved(collection="noaa_ghcnd")) + + _, metadata = await client.load_entities(collection="ghcnd", dataset="daily") + + assert metadata["collection"] == "noaa_ghcnd" + assert metadata["organization"] == "noaa" + assert metadata["slug"] == "noaa_ghcnd/daily/default" diff --git a/tests/test_review_suspects.py b/tests/test_review_suspects.py index 1992f06..8c9e969 100644 --- a/tests/test_review_suspects.py +++ b/tests/test_review_suspects.py @@ -724,3 +724,34 @@ def test_catalog_lister_keeps_bare_item_with_default_variant_property(): assert variant["dataset"] == "precip-daily" assert variant["variant"] == "default" + + +def test_stac_server_collections_raises_when_page_limit_would_truncate(monkeypatch): + """ + Every ``/collections`` page advertises another next link, so the walk can + never terminate naturally. Returning what it had would hand back a + catalogue that looks complete, with the missing collections showing up + later as untitled or unknown datasets rather than as this failure. + """ + monkeypatch.setattr(stac_server, "_MAX_SEARCH_PAGES", 2) + calls = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal calls + calls += 1 + return httpx.Response( + 200, + json={ + "collections": [{"id": f"coll-{calls}", "title": f"Coll {calls}"}], + "links": [{"rel": "next", "href": f"/collections?page={calls + 1}"}], + }, + request=request, + ) + + assert _install_mock_client is not None + _install_mock_client(stac_server, handler) + + with pytest.raises(ValueError, match="truncated"): + stac_server._fetch_all_collections("https://example.test") + + assert calls == 2 diff --git a/tests/test_stac_server_listing.py b/tests/test_stac_server_listing.py index a134d3e..0a5b824 100644 --- a/tests/test_stac_server_listing.py +++ b/tests/test_stac_server_listing.py @@ -491,3 +491,75 @@ def test_organization_derived_from_underscore_prefix(monkeypatch): result = list_available_datasets_from_stac_server("https://example.test") assert result["single"]["organization"] is None assert result["org_thing"]["organization"] == "org_thing".split("_")[0] + + +def test_collections_pagination_follows_next(monkeypatch): + """``/collections`` paginates, and only the first page arrived. + + The endpoint defaults to a page size smaller than the catalogue, so a single + unpaged request returns a well-formed but short list. The collections past + the first page are not obviously missing -- they simply arrive with no title + or organization, because this endpoint is their only source. That surfaced + as a live parity test failing on the 11th collection of 14. + """ + requested: list[str] = [] + + page_two = {"collections": [{"id": "noaa_gfs", "title": "NOAA GFS Forecast"}]} + page_one = { + "collections": [{"id": "ecmwf_era5", "title": "ECMWF ERA5 Reanalysis"}], + "links": [{"rel": "next", "href": "https://stac.test/collections?offset=1"}], + "numberMatched": 2, + "numberReturned": 1, + } + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + requested.append(str(request.url)) + body = page_two if "offset=1" in str(request.url) else page_one + return _mock_response(request, body) + return _mock_response(request, SAMPLE_SEARCH) + + assert _install_mock_client is not None + _install_mock_client(stac_server, handler) + + result = list_available_datasets_from_stac_server("https://stac.test") + + assert any("offset=1" in url for url in requested), ( + "second page was never requested" + ) + # The collection from page two must carry the title only /collections knows. + assert result["noaa_gfs"]["title"] == "NOAA GFS Forecast" + + +def test_collections_pagination_raises_at_foreign_origin(monkeypatch): + """A ``next`` pointing off-origin would walk the client out of its server. + + So it is never followed -- a redirect chain could otherwise steer catalogue + reads to a host the caller never configured. But it is not dropped silently + either: that would end the walk exactly like a server saying it was + finished, returning a truncated catalogue that looks whole. Refusing the + link keeps the boundary; raising keeps the truncation visible. + """ + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + if "evil.test" in str(request.url): + raise AssertionError(f"followed next off-origin: {request.url}") + return _mock_response( + request, + { + "collections": [ + {"id": "ecmwf_era5", "title": "ECMWF ERA5 Reanalysis"} + ], + "links": [{"rel": "next", "href": "https://evil.test/collections"}], + }, + ) + return _mock_response(request, SAMPLE_SEARCH) + + assert _install_mock_client is not None + _install_mock_client(stac_server, handler) + + # The boundary held: the off-origin href was reported, never fetched. + # (Had it been requested, the handler would have raised AssertionError.) + with pytest.raises(ValueError, match="configured server origin"): + list_available_datasets_from_stac_server("https://stac.test") diff --git a/tests/test_stac_version_discovery.py b/tests/test_stac_version_discovery.py index 90d1157..a19e7d3 100644 --- a/tests/test_stac_version_discovery.py +++ b/tests/test_stac_version_discovery.py @@ -1,6 +1,7 @@ from unittest.mock import Mock import pytest +from dataclasses import replace import pystac import xarray as xr import httpx @@ -411,7 +412,11 @@ async def test_version_catalog_fallback_normalizes_shorthand_collection(monkeypa organization=None, ) - assert details is resolved + # The resolver's payload is passed through unchanged except for the + # identity the expansion just established: `era5` was matched against the + # catalogue as `ecmwf_era5`, and that is the name callers must report. + assert details == replace(resolved, collection="ecmwf_era5") + assert details.collection == "ecmwf_era5" resolver.assert_called_once_with( catalog=catalog, collection="ecmwf_era5", diff --git a/uv.lock b/uv.lock index 6390360..493ab3a 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 2 requires-python = ">=3.12" resolution-markers = [ "python_full_version >= '3.15'", @@ -677,11 +677,12 @@ wheels = [ [[package]] name = "dclimate-client-py" -version = "0.7.0" +version = "0.8.0" source = { editable = "." } dependencies = [ { name = "aiobotocore" }, { name = "aiohttp" }, + { name = "dclimate-tabular-py" }, { name = "geopandas" }, { name = "httpx" }, { name = "multiformats" }, @@ -721,6 +722,7 @@ testing = [ requires-dist = [ { name = "aiobotocore", specifier = ">=2.13.0" }, { name = "aiohttp", specifier = ">=3.9.0" }, + { name = "dclimate-tabular-py", specifier = ">=0.2.1" }, { name = "geopandas", specifier = ">=1.0.0" }, { name = "httpx", specifier = ">=0.27.0" }, { name = "multiformats", specifier = ">=0.3.1" }, @@ -749,6 +751,23 @@ requires-dist = [ ] provides-extras = ["testing", "dev", "examples"] +[[package]] +name = "dclimate-tabular-py" +version = "0.2.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "blake3" }, + { name = "dag-cbor" }, + { name = "httpx" }, + { name = "multiformats", extra = ["full"] }, + { name = "py-hamt" }, + { name = "pyarrow" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/88/14/7ffdf05196e15aa22a9e7561a58171b6145501ef6bad8ddefa0ea303b453/dclimate_tabular_py-0.2.1.tar.gz", hash = "sha256:95f738b026e033a07eaae0588009a0b35857f17998d5bcdb082baa0ddf2207bf", size = 157341, upload-time = "2026-08-27T16:57:24.049Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/89/9bf065ae8bc8f22303822a91e31ac80f12c8539f906c6c749b92a5ef9b3a/dclimate_tabular_py-0.2.1-py3-none-any.whl", hash = "sha256:31f6e189fc975d7d25ad83a8002a1cbadc70094b497f1a313b1c46cd10ff8aa4", size = 58022, upload-time = "2026-08-27T16:57:22.852Z" }, +] + [[package]] name = "deprecated" version = "1.2.18" @@ -1647,6 +1666,42 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c1/f3/8ea8b9d21e0b36490bff3e3524994d64d3365ef184138f2b568fa0326ed7/py_hamt-3.6.0-py3-none-any.whl", hash = "sha256:9b20fa474b84f5a112ebd61093fbab2613117b0ede8fa4fd5114605110e647da", size = 81309, upload-time = "2026-07-30T12:15:33.917Z" }, ] +[[package]] +name = "pyarrow" +version = "25.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3d/e3/27f57f80141379d60defe6703eb50a707325706f07fedfd1312c7a751995/pyarrow-25.0.1.tar.gz", hash = "sha256:9150a83248bfed9813ea3c3af74c3856c1984d444aa28e58bf7733b9750ddf6a", size = 1201653, upload-time = "2026-08-10T12:40:53.904Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a6/e2/9ab15b88cbfac28e16419ce5439ec29234c5172cb8259301b4ba639bdec0/pyarrow-25.0.1-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:df961f2e7ae9cf496459259d798652c70625f6c080650d6952f8c04053c58ee9", size = 35861559, upload-time = "2026-08-10T12:38:02.567Z" }, + { url = "https://files.pythonhosted.org/packages/58/79/a0036dbe1eabe1f73127427342f1d99982584c4a2cde2651d6c93499c6f6/pyarrow-25.0.1-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:cc4aa407fde9fc660be3939e49ea31f50f3e9fec17c0ec63159f7711edd3efc9", size = 37628383, upload-time = "2026-08-10T12:38:09.083Z" }, + { url = "https://files.pythonhosted.org/packages/13/49/d93a57d375f4bf0cf82913dd6bb54acafde83dd993be2282c81ac5616cad/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:4340f0ba6c1d2e13f21658de1d7c662ca2545018568d0030a1e9afca159d87e3", size = 46820190, upload-time = "2026-08-10T12:38:15.458Z" }, + { url = "https://files.pythonhosted.org/packages/60/c9/711ca85d79f1ec98f29a5eae2b051e25b4ecec5de3e3c0e2d5c5dcb15664/pyarrow-25.0.1-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:5389cdf79447ed1515c9e31620e6e1e2302249564d603f2ad727d4f6d313e4c3", size = 50102437, upload-time = "2026-08-10T12:38:22.487Z" }, + { url = "https://files.pythonhosted.org/packages/80/53/8fb8359ff17cfb6263a1cf3ebf7caec9fe197de118719e84fcb1d0618026/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d51592cb7561e87877c506113e7adbf1342ab579e6c21f0ef44b8ba41cb74c80", size = 49942424, upload-time = "2026-08-10T12:38:28.755Z" }, + { url = "https://files.pythonhosted.org/packages/e8/83/4e5ae02a9341571b18a6fca380ac7a58ce6ddae7ab3c060208c0a1e79f02/pyarrow-25.0.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6109c94d8b9f3b17a041daca16cacb2f651ad8f1ef70a4232c2c0f37a23da2a8", size = 53144206, upload-time = "2026-08-10T12:38:34.862Z" }, + { url = "https://files.pythonhosted.org/packages/65/ee/197cbf47e49f83e6ebeb946a5259a48a638dea27ac774db42fe78022179d/pyarrow-25.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:8858d7bfc22e3f51529aeaa4077225029724623e4595dc9eff8c793935c34140", size = 27953934, upload-time = "2026-08-10T12:38:39.808Z" }, + { url = "https://files.pythonhosted.org/packages/cc/8d/8f271a7a034c834910ec925d56fa4b29733b1380f5289419f5aaa3b02777/pyarrow-25.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:c7c534ec03c358a76ea3e505e74c1b6aef290af90c444dfd092dbfe23e755b85", size = 35855328, upload-time = "2026-08-10T12:38:45.489Z" }, + { url = "https://files.pythonhosted.org/packages/d2/cd/5bac242f4e841b9971d5eb94fdfe2577e2b70be983e27401e72055786037/pyarrow-25.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:dda9470024204d7bbf2042b47c6e8a0e47a3eeb8e34405882dfaea6577e0c153", size = 37622415, upload-time = "2026-08-10T12:38:51.107Z" }, + { url = "https://files.pythonhosted.org/packages/63/1f/96d03b4e1506524f7087adb0fd6b2f69f0c9c7aaff1ec36d8030082e15a5/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:44a9120ce5bd81936b8ab9a88076e3fd47c2c6838e0e43630fed83626aca81d9", size = 46813813, upload-time = "2026-08-10T12:38:57.773Z" }, + { url = "https://files.pythonhosted.org/packages/98/d6/33a411115b61dbfc16ad6ad73e71730f6fea654ee3667673bc53ab0e2fe7/pyarrow-25.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:0befcf816e45a1af33ac775a9970b749e4868a230c7372f0ae5e932bee27039f", size = 50104452, upload-time = "2026-08-10T12:39:04.579Z" }, + { url = "https://files.pythonhosted.org/packages/33/ae/b1b97c9ca87f9f9ddbb5230c798df94eccce61bd79b9b45458c69a478588/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3f89685964f46e4216103c75483aac0c0692a5f72212d7ca835adba5ede56ce3", size = 49951343, upload-time = "2026-08-10T12:39:11.8Z" }, + { url = "https://files.pythonhosted.org/packages/98/9e/a112df5cfd5a68cb1d9fc31cfe38c28d5aec9f10865ce37ecef2e4450873/pyarrow-25.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6943e2fe7954d29d84de45d29d34c8dc36ce96570e67d89aa9976e650a4a9138", size = 53144784, upload-time = "2026-08-10T12:39:20.503Z" }, + { url = "https://files.pythonhosted.org/packages/31/24/97e8bd98f1e3b07e2ba08bcdff690674fbe16d69a7d2712cc3884665e615/pyarrow-25.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:31e49a7888fcdf3a835da33ae777f6bb9a866334e5a789282fc26dcf426f7f15", size = 27870159, upload-time = "2026-08-10T12:39:26.161Z" }, + { url = "https://files.pythonhosted.org/packages/36/4c/b525824ad3094076919273cd97db61fb3d78252dee76fa3b8dc8f76774aa/pyarrow-25.0.1-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:bf0b672390cdcb640d7288f96b826d71ff4e9abb254a86c89890baf51a29cee6", size = 35885255, upload-time = "2026-08-10T12:39:32.366Z" }, + { url = "https://files.pythonhosted.org/packages/08/62/448bb0e940de41aec31d1a956e63ad9c54afdf122a103cc3ab20c2a3ce33/pyarrow-25.0.1-cp314-cp314-macosx_12_0_x86_64.whl", hash = "sha256:38a9a4b4b9613380e200641891495a56c3d5a98a092db4a870af9975e220471d", size = 37644461, upload-time = "2026-08-10T12:39:38.142Z" }, + { url = "https://files.pythonhosted.org/packages/6e/9a/13587e38bd4806fd218f50fd13b8903fab60588a699ff0c406372e5b4043/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:0b726ad7e7b669be982b0c71c07fe4b037d654354130da79a7902a669e93a66b", size = 46877146, upload-time = "2026-08-10T12:39:43.722Z" }, + { url = "https://files.pythonhosted.org/packages/8d/61/1c5d1229fa21da4cff5365e41e57177aaac57c563c727f35419b8513d1c1/pyarrow-25.0.1-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:9171748cdf796972d85a4b60157c279913e242992e350c90c7450182a9838b2a", size = 50131616, upload-time = "2026-08-10T12:39:49.304Z" }, + { url = "https://files.pythonhosted.org/packages/43/20/291e1d65cc0b09aa19f03cf25cf51a2f5fa94b5db315178f2d254ed5cad4/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:b7a296aac7a71fa0886c08e155ddb6c636a50013f801f6178daafa0f9e726188", size = 50008879, upload-time = "2026-08-10T12:39:56.891Z" }, + { url = "https://files.pythonhosted.org/packages/8b/7c/1b7c9ec28e76576337e4f97b31141c9a181b89b6d1d6221e9d8205621a58/pyarrow-25.0.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:0fe7c8b6c03969b49c8c66182e4a18e3819ab92d07cfab5d8370c531b9369ef0", size = 53170864, upload-time = "2026-08-10T12:40:04.918Z" }, + { url = "https://files.pythonhosted.org/packages/b7/75/f3d789dc06011a765d14d86bda799cf72ac1d715b6a6edecaa0d73d95062/pyarrow-25.0.1-cp314-cp314-win_amd64.whl", hash = "sha256:f729cfdbd36fd99d543b67a914d2de044c84ebe45be8b34902b299b608c15c8f", size = 28620729, upload-time = "2026-08-10T12:40:51.41Z" }, + { url = "https://files.pythonhosted.org/packages/fc/05/647a8ee6f7c2662feb6921315617bc04dcd6034763fb61b1199720bf6162/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:59a2de54c0cbd954da861eee4d1d330f8e909c45b53455baef696380f2c55033", size = 36130288, upload-time = "2026-08-10T12:40:11.014Z" }, + { url = "https://files.pythonhosted.org/packages/93/f8/c9ee997554d7bea94520667dd1933f109ac1da3ee3556d2b49381e023484/pyarrow-25.0.1-cp314-cp314t-macosx_12_0_x86_64.whl", hash = "sha256:35935cd5de130aa5cf4dea052a63e6bf2e17006c35c3a468194242b9b2bf5956", size = 37762187, upload-time = "2026-08-10T12:40:16.592Z" }, + { url = "https://files.pythonhosted.org/packages/a2/08/a28c01c7fe9e96e8233ce2d13df1d402f4f999f848f51d2daacd6bb4c036/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:f3831aaa25c67a99f99dc8b05873cb9d64560390372e2aa197ce9dd4a3f06a44", size = 46888003, upload-time = "2026-08-10T12:40:23.242Z" }, + { url = "https://files.pythonhosted.org/packages/1b/b9/58612e977d28dc58c878448866838369ee8da2f1e7cc8ed2c84b952aafee/pyarrow-25.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:6a1fdfc6659b6b19022f2e50627fb5cf7156a66c46bf4299379955cbe742382a", size = 50079036, upload-time = "2026-08-10T12:40:29.169Z" }, + { url = "https://files.pythonhosted.org/packages/72/13/66e1402dcc860e1dc2760b1e0292c9a569b62b3bccab69def1b3e907d006/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:169d3429d5be7c752125890620f75a60776d38b0035eddae939651640822332e", size = 50040226, upload-time = "2026-08-10T12:40:35.186Z" }, + { url = "https://files.pythonhosted.org/packages/78/10/3f1a5497a7ef732ab0f03ecca3e66d89d9c0f57fdc61b4794c456b781f01/pyarrow-25.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:119297a6dc197e45d9c6d4415f7814a67ffa36c180d26f68c154c58067ae782d", size = 53149035, upload-time = "2026-08-10T12:40:41.454Z" }, + { url = "https://files.pythonhosted.org/packages/93/c0/37d4a7e8e2f7a6076283673d5298018ca26478b934c6ee369e10505ab32c/pyarrow-25.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:4288f27577352d608ca08553b0865e4a9b3aa14820c5d95b53337218d609835b", size = 28753071, upload-time = "2026-08-10T12:40:46.623Z" }, +] + [[package]] name = "pycryptodome" version = "3.22.0"