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..d8b82f2 100644 --- a/dclimate_client_py/dclimate_client.py +++ b/dclimate_client_py/dclimate_client.py @@ -40,6 +40,7 @@ list_versions_from_url, ) from .siren import SirenClient +from .entities import EntitiesClient from .siren.types import ( SirenMetricDataPoint, SirenMetricQuery, @@ -170,6 +171,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 +222,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) @@ -848,6 +866,39 @@ async def get_dataset_version( commit_id, ) + # ------------------------------------------------------------------ + # Entity (point-observation) datasets + # ------------------------------------------------------------------ + + @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..7c5599d --- /dev/null +++ b/dclimate_client_py/entities/entities_client.py @@ -0,0 +1,226 @@ +"""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] = [] + + 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 = [] + + 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) + source = tabular.GatewayRangeSource(gateway_url or self._gateway_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) + 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. Catalog resolution is not " + "available yet." + ) + + 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, [] + 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..4892b52 --- /dev/null +++ b/dclimate_client_py/entities/errors.py @@ -0,0 +1,95 @@ +"""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. + 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/pyproject.toml b/pyproject.toml index 53385ce..83f3eb2 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.0", "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..5f4d5b6 --- /dev/null +++ b/tests/test_entities.py @@ -0,0 +1,477 @@ +"""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, + 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_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")], + ) + 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/uv.lock b/uv.lock index 6390360..e46f0e9 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.0" }, { 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.0" +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/f9/e3/ae940fe264527d5d480d44033bfa378f78bc7eb6eecc5dac23039c54252e/dclimate_tabular_py-0.2.0.tar.gz", hash = "sha256:ad12783017b018cfc0a76b8fd501f21e85f4b047b71a8e918be395e06a563bd0", size = 156803, upload-time = "2026-08-26T15:34:06.224Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/e1/06778e24609a3d5767309a5590606a35ad0b21ae0c21c6967a59ba2e71a3/dclimate_tabular_py-0.2.0-py3-none-any.whl", hash = "sha256:feacb6086a6a06939960f6e193246e6c9dd1128ce1a6b8d71cdde470ed0814e9", size = 57834, upload-time = "2026-08-26T15:34:05.061Z" }, +] + [[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"