From f426ba7933f4c65b5d5d89e1ffaebdeefbc123c8 Mon Sep 17 00:00:00 2001 From: TheGreatAlgo <37487508+TheGreatAlgo@users.noreply.github.com> Date: Thu, 13 Aug 2026 12:29:26 -0400 Subject: [PATCH 1/4] feat: station data support via client.stations Mirrors the `client.stations` namespace from dclimate-client-js (PR #10), built on tabular-py. Gridded Zarr datasets still come from `load_dataset`; point-observation station datasets (GHCND and friends) read the same way -- degrees, ISO timestamps, chained selections: async with dClimateClient() as client: stations = await client.stations.load(cid) rows = await stations.select("USW00093134").time_range(a, b).rows() # Or resolve dataset and station in one call, which is the question most # callers open a station dataset to ask: st = await client.stations.nearest(cid, lat, lon, columns=["TMAX"]) Two things differ from the JS client, both because the Python side can do better rather than because parity slipped: - Reads prefer the client's own KuboCAS over a second HTTP path, so pinning, retries and configured endpoints apply to station reads too. Outside the async context there is no KuboCAS yet, so it falls back to the plain gateway. - `nearest` takes `columns=` to mean nearest station *with usable data*. Without it, near downtown LA the closest station is 0.63 km away and has never recorded TMAX, while the closest that has is 5.4 km away. Errors are translated at the boundary, so everything escaping the client is a ZarrClientError: an unknown column is InvalidSelectionError, a well-formed query matching nothing is NoDataFoundError, and unreadable bytes are the new DatasetCorruptError -- distinct because it points at the publisher rather than the caller. Transport failures deliberately pass through untranslated: a gateway timeout is retryable and says nothing about the dataset. The translation covers the whole chain, not just `load`. `select`, `where` and `rows` raise tabular's errors too, and they are where a caller is far likelier to meet one; WrappedStationDataset forwards attribute access and re-wraps returned datasets so the boundary does not stop at the first link. tabular-py is not on PyPI yet, so it is deliberately neither a dependency nor an extra: uv resolves every extra when locking, so naming an unpublished package makes `uv sync` fail even for people who never touch station data. `client.stations` raises TabularNotInstalledError with install instructions until then, and the package imports cleanly without it. Verified end to end against bafyr4if2wbttslbxpzmro427j4l4nvcrxqo4tufuffqqmqz7afj2pxyu4a, including every README example and each error-translation path. --- README.md | 91 ++++++ dclimate_client_py/__init__.py | 17 + dclimate_client_py/dclimate_client.py | 39 +++ dclimate_client_py/dclimate_zarr_errors.py | 16 + dclimate_client_py/stations/__init__.py | 17 + dclimate_client_py/stations/errors.py | 94 ++++++ .../stations/stations_client.py | 172 ++++++++++ dclimate_client_py/stations/wrap.py | 104 ++++++ pyproject.toml | 10 + tests/test_stations.py | 301 ++++++++++++++++++ 10 files changed, 861 insertions(+) create mode 100644 dclimate_client_py/stations/__init__.py create mode 100644 dclimate_client_py/stations/errors.py create mode 100644 dclimate_client_py/stations/stations_client.py create mode 100644 dclimate_client_py/stations/wrap.py create mode 100644 tests/test_stations.py diff --git a/README.md b/README.md index 6df49eb..64f5210 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,97 @@ 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. +## Station data usage + +Gridded Zarr datasets come from `load_dataset`. Point-observation **station** +datasets (GHCND and friends) live under `client.stations`, and read the same way: +degrees, ISO timestamps, chained selections. + +Station support needs [`tabular-py`](https://github.com/dClimate/tabular-py), +which is not on PyPI yet, so it is not installed by default: + +``` shell +uv pip install git+https://github.com/dClimate/tabular-py +``` + +Until it is installed, `client.stations` raises `TabularNotInstalledError` with +those instructions. Once `tabular-py` is published it moves into the ordinary +dependency list, matching `dclimate-client-js`. + +```python +async with dClimateClient() as client: + stations = await client.stations.load("bafyr4i...") + + # Every station, with position and coverage window. + for s in await stations.list_stations(): + print(s.station_id, s.latitude, s.longitude, s.start, s.end) + + # Stations within 50 km of a point, over one week. + records = await ( + stations + .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 station reads too. Resolution is by CID for now; +STAC catalog support will follow. + +Selections return new instances, so a partial selection can be branched: + +```python +week = stations.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; stations 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 station index to find the match, so it is awaited -- +# unlike the synchronous selections above. +hot_days = await ( + (await stations.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 *station*, 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 station in one call. +station = await client.stations.nearest( + "bafyr4i...", + 34.0522, -118.2437, + columns=["TMAX"], + within=("2024-01-01", "2024-12-31"), + max_km=50, +) +print(station.station_id, station.km) +``` + +Station 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..76d99fa 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"), + "StationsClient": (".stations", "StationsClient"), + "WrappedStationDataset": (".stations", "WrappedStationDataset"), "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", + # Stations + "StationsClient", + "WrappedStationDataset", + "TabularNotInstalledError", ] diff --git a/dclimate_client_py/dclimate_client.py b/dclimate_client_py/dclimate_client.py index 2e55e1a..3512931 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 .stations import StationsClient from .siren.types import ( SirenMetricDataPoint, SirenMetricQuery, @@ -170,6 +171,10 @@ def __init__( if siren is not None: self._siren_client = SirenClient(siren) + # Station datasets. Unlike Siren this needs no configuration, so it is + # built on first access rather than here -- see the `stations` property. + self._stations_client: typing.Optional["StationsClient"] = None + async def __aenter__(self) -> "dClimateClient": """Initialize KuboCAS when entering async context.""" # Create KuboCAS with configured endpoints @@ -217,6 +222,12 @@ 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._stations_client is not None: + await self._stations_client.aclose() + except BaseException as error: + cleanup_error = _merge_cleanup_error(cleanup_error, error) + try: if self._kubo_cas is not None: await self._kubo_cas.__aexit__(exc_type, exc_val, exc_tb) @@ -848,6 +859,34 @@ async def get_dataset_version( commit_id, ) + # ------------------------------------------------------------------ + # Station (point-observation) datasets + # ------------------------------------------------------------------ + + @property + def stations(self) -> StationsClient: + """Station datasets, e.g. ``await client.stations.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 station 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 + if self._stations_client is None or ( + cas is not None and self._stations_client._cas is not cas + ): + self._stations_client = StationsClient( + gateway_url=self._catalog_gateway_base_url, + cas=cas, + ) + return self._stations_client + # ------------------------------------------------------------------ # Siren REST API methods # ------------------------------------------------------------------ diff --git a/dclimate_client_py/dclimate_zarr_errors.py b/dclimate_client_py/dclimate_zarr_errors.py index c23f5a8..33bd54d 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 station data is requested but tabular-py is not installed""" diff --git a/dclimate_client_py/stations/__init__.py b/dclimate_client_py/stations/__init__.py new file mode 100644 index 0000000..5c38560 --- /dev/null +++ b/dclimate_client_py/stations/__init__.py @@ -0,0 +1,17 @@ +"""Station (point-observation) dataset support, built on ``tabular-py``. + +Everything here imports without ``tabular_py`` installed; the dependency is only +required once a dataset is actually loaded, which is what lets the rest of the +library import cleanly when the optional extra is absent. +""" + +from .errors import translate_station_error +from .stations_client import StationsClient +from .wrap import WrappedStationDataset, wrap_station_dataset + +__all__ = [ + "StationsClient", + "WrappedStationDataset", + "translate_station_error", + "wrap_station_dataset", +] diff --git a/dclimate_client_py/stations/errors.py b/dclimate_client_py/stations/errors.py new file mode 100644 index 0000000..c479cc2 --- /dev/null +++ b/dclimate_client_py/stations/errors.py @@ -0,0 +1,94 @@ +"""Translating ``tabular-py`` failures into this library's error types. + +Mirrors ``dclimate-client-js`` ``src/stations/errors.ts``. + +Station 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 station +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_station_error(cause: BaseException) -> NoReturn: + """Re-raise a station 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 station, 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 require the optional dependency. + from tabular_py.errors import ( + DatasetIntegrityError, + DatasetReaderError, + DclimateTabularError, + PredicateError, + RangeSourceError, + StationSelectionError, + ) + + if isinstance(cause, StationSelectionError): + 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/stations/stations_client.py b/dclimate_client_py/stations/stations_client.py new file mode 100644 index 0000000..003fd62 --- /dev/null +++ b/dclimate_client_py/stations/stations_client.py @@ -0,0 +1,172 @@ +"""Station (point-observation) datasets, as opposed to the gridded Zarr datasets. + +Mirrors ``dclimate-client-js`` ``src/stations/stations-client.ts``. + +The two are different enough underneath -- irregular stations with per-station +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. ``StationDataset`` 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 station 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_station_error +from .wrap import WrappedStationDataset, wrap_station_dataset + +if typing.TYPE_CHECKING: # pragma: no cover + from collections.abc import Sequence + + from py_hamt import KuboCAS + from tabular_py import NearestStation + from tabular_py.station_dataset import TimeInput + + +def _require_tabular() -> typing.Any: + """Import ``tabular_py``, or explain how to install it. + + Optional only because ``tabular-py`` is not on PyPI yet; the JS client + depends on ``@dclimate/tabular`` unconditionally. + """ + try: + import tabular_py + except ImportError as cause: + raise TabularNotInstalledError( + "Station data requires tabular-py, which is not on PyPI yet. " + "Install it with:\n" + " uv pip install git+https://github.com/dClimate/tabular-py" + ) from cause + return tabular_py + + +class StationsClient: + """Loads station 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 _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, + ) -> WrappedStationDataset: + """Open a station dataset by root CID. + + Reads go through the IPFS HTTP gateway, so this needs no local daemon. + """ + if not cid: + raise DatasetNotFoundError( + "A station 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) + # 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_station_dataset(await tabular.StationDataset.open(source, root)) + except BaseException as cause: + translate_station_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, + ) -> NearestStation: + """The station nearest a point that actually has the data you asked for. + + Resolves the dataset and the station in one call, because "which station + should I use for this location" is the question most callers open a + station 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 stations that actually report every + one of those columns. Without it, "nearest" means nearest *station*, 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 station reported the + column at some point, not that it reported it recently; pass ``within`` + to narrow that to a time range. + + Returns the distance alongside the station: a dataset with no coverage + near the queried point still has a nearest station, 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) + # Already wrapped, so failures here arrive as this library's errors. + return typing.cast( + "NearestStation", + await dataset.find_nearest_station( + 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. + """ + sources, self._owned_sources = self._owned_sources, [] + for source in sources: + await source.aclose() diff --git a/dclimate_client_py/stations/wrap.py b/dclimate_client_py/stations/wrap.py new file mode 100644 index 0000000..13c41db --- /dev/null +++ b/dclimate_client_py/stations/wrap.py @@ -0,0 +1,104 @@ +"""Keeping the error boundary closed across a whole selection chain. + +Mirrors ``dclimate-client-js`` ``src/stations/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 station, ``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* ``StationDataset`` 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``) -> re-wrap +* async chainable (``nearest``) -> re-wrap on await +* async terminal (``rows``, ``plan``, ``list_stations``) -> translate the raise +""" + +from __future__ import annotations + +import functools +import inspect +from typing import TYPE_CHECKING, Any + +from .errors import translate_station_error + +if TYPE_CHECKING: # pragma: no cover + from tabular_py import StationDataset + + +class WrappedStationDataset: + """A :class:`~tabular_py.StationDataset` 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: StationDataset) -> None: + object.__setattr__(self, "_dataset", dataset) + + @property + def unwrapped(self) -> StationDataset: + """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_station_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_station_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 StationDataset + + if isinstance(value, StationDataset): + return WrappedStationDataset(value) + return value + + +def wrap_station_dataset(dataset: StationDataset) -> WrappedStationDataset: + """Wrap a dataset so every method failure comes back as a ``ZarrClientError``.""" + return WrappedStationDataset(dataset) diff --git a/pyproject.toml b/pyproject.toml index 53385ce..77fafd4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,6 +29,16 @@ classifiers = [ "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [ + # NOTE: station data (`client.stations`) needs `tabular-py`, which is not on + # PyPI yet. It is deliberately *not* declared here or as an extra: uv + # resolves every extra when locking, so naming an unpublished package makes + # even `uv sync` fail for people who never touch station data. Install it + # alongside for now -- + # uv pip install git+https://github.com/dClimate/tabular-py + # -- and move it into this list once it is published, matching + # dclimate-client-js, which depends on @dclimate/tabular unconditionally. + # `client.stations` raises TabularNotInstalledError with these instructions + # until then. "aiobotocore>=2.13.0", "aiohttp>=3.9.0", "xarray>=2025.3.0", diff --git a/tests/test_stations.py b/tests/test_stations.py new file mode 100644 index 0000000..ae0b584 --- /dev/null +++ b/tests/test_stations.py @@ -0,0 +1,301 @@ +"""Station dataset support: the client namespace and the error boundary. + +Mirrors ``dclimate-client-js`` ``tests/stations.test.ts`` and +``tests/stations-wrap.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.stations import StationsClient + +tabular_py = pytest.importorskip( + "tabular_py", + reason="station support needs tabular-py, which is not on PyPI yet", +) + +from tabular_py.errors import ( # noqa: E402 + CodecError, + DatasetIntegrityError, + DatasetReaderError, + PredicateError, + RangeSourceError, + StationSelectionError, + WireError, +) + +from dclimate_client_py.stations.errors import translate_station_error # noqa: E402 +from dclimate_client_py.stations.wrap import wrap_station_dataset # noqa: E402 + +# A real, published GHCND station dataset. +REAL_CID = "bafyr4if2wbttslbxpzmro427j4l4nvcrxqo4tufuffqqmqz7afj2pxyu4a" + + +def fake(**overrides: object) -> tabular_py.StationDataset: + """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 + ``StationDataset`` instance so the wrapper's ``isinstance`` re-wrapping check + sees what it would see in production. + """ + dataset = object.__new__(tabular_py.StationDataset) + 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; station 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.stations, StationsClient) + + def test_reuses_one_instance_across_accesses(self) -> None: + client = dClimateClient() + assert client.stations is client.stations + + 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") + + stations = StationsClient(gateway_url="http://127.0.0.1:8080") + stations._source = lambda _gateway: Recording() # type: ignore[method-assign] + + with pytest.raises(DatasetNotFoundError): + await stations.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.stations.load("") + + async def test_routes_reads_through_the_gateway_it_was_given(self) -> None: + stations = StationsClient(gateway_url="https://gateway.example") + source = stations._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 stations.aclose() + + async def test_a_per_request_gateway_overrides_the_client_default(self) -> None: + stations = StationsClient(gateway_url="https://default.example") + source = stations._source("https://override.example") + assert "override.example" in repr(source.__dict__) + await stations.aclose() + + def test_prefers_the_clients_own_cas_when_open(self) -> None: + sentinel = object() + stations = StationsClient(gateway_url="https://unused.example", cas=sentinel) + source = stations._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: + stations = StationsClient(gateway_url="https://default.example", cas=object()) + source = stations._source("https://override.example") + assert isinstance(source, tabular_py.GatewayRangeSource) + + +class TestTranslateStationError: + """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_station_error(StationSelectionError("no match", "not-found")) + + def test_invalid_selection_becomes_invalid_selection(self) -> None: + with pytest.raises(InvalidSelectionError): + translate_station_error(StationSelectionError("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_station_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_station_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_station_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_station_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_station_error(original) + assert raised.value is original + + def test_message_is_preserved_verbatim(self) -> None: + # The message is the only part naming the station, column, or distance + # that actually failed. + with pytest.raises(InvalidSelectionError, match="column 'TMPX' at row 12"): + translate_station_error(DatasetReaderError("column 'TMPX' at row 12")) + + +class TestWrapStationDataset: + """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_station_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 StationSelectionError("no match", "not-found") + + dataset = wrap_station_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_station_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_station_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__ == "WrappedStationDataset" + + 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_station_dataset(fake(nearest=nearest)) + selected = await dataset.nearest(34.0, -118.0) + assert type(selected).__name__ == "WrappedStationDataset" + with pytest.raises(InvalidSelectionError): + await selected.rows() + + async def test_passes_plain_data_through_untouched(self) -> None: + payload = [{"station_id": "USW00023174", "value": 3}] + + async def rows() -> list[object]: + return payload + + dataset = wrap_station_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_station_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_station_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 station failures too. + for cause in ( + DatasetReaderError("bad"), + StationSelectionError("gone", "not-found"), + DatasetIntegrityError("corrupt"), + WireError("not a root"), + ): + + async def rows(_cause: Exception = cause) -> list[object]: + raise _cause + + dataset = wrap_station_dataset(fake(rows=rows)) + with pytest.raises(ZarrClientError): + await dataset.rows() + + +class TestOptionalDependency: + def test_absence_is_reported_with_install_guidance(self, monkeypatch) -> None: + import builtins + + from dclimate_client_py.stations import stations_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) + with pytest.raises(TabularNotInstalledError, match="tabular-py"): + stations_client._require_tabular() From d84a874a3d5dba30c2adfd1f399ad7625c2ef122 Mon Sep 17 00:00:00 2001 From: TheGreatAlgo <37487508+TheGreatAlgo@users.noreply.github.com> Date: Thu, 13 Aug 2026 13:52:22 -0400 Subject: [PATCH 2/4] chore: depend on dclimate-tabular-py from PyPI PyPI rejects the name `tabular-py`: it normalises onto the unrelated existing `tabularpy` project. The distribution is namespaced to `dclimate-tabular-py` instead, matching @dclimate/tabular on npm. The import name is unchanged -- `tabular_py` -- since PyPI has no opinion about it and renaming the module would churn both repos for nothing. Now that it is published, station support is an ordinary dependency rather than an install-it-yourself note, matching dclimate-client-js's unconditional dependency on @dclimate/tabular. `uv sync` resolves it from the registry, so the earlier problem -- naming an unpublished package made even a plain sync fail -- is gone. `_require_tabular` and TabularNotInstalledError are kept, with the message rewritten. They no longer guard an optional extra; they exist because the import name and the distribution name differ, so a stock ModuleNotFoundError would name `tabular_py`, which `pip install` cannot find. The test now asserts the message names the installable distribution, which is the failure mode that actually matters. Verified from a clean Python 3.12 environment with no cache: the client installs, pulls dclimate-tabular-py 0.1.0 from pypi.org, imports as tabular_py, and resolves client.stations. 298 tests pass there, up from 292 -- six of the previously reported failures were local environment damage (root-owned .venv and build directories), not code. --- README.md | 15 ++--- dclimate_client_py/stations/__init__.py | 9 +-- dclimate_client_py/stations/errors.py | 3 +- .../stations/stations_client.py | 16 +++-- pyproject.toml | 16 ++--- tests/test_stations.py | 11 ++-- uv.lock | 59 ++++++++++++++++++- 7 files changed, 92 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 64f5210..a1bdbf5 100644 --- a/README.md +++ b/README.md @@ -233,16 +233,11 @@ Gridded Zarr datasets come from `load_dataset`. Point-observation **station** datasets (GHCND and friends) live under `client.stations`, and read the same way: degrees, ISO timestamps, chained selections. -Station support needs [`tabular-py`](https://github.com/dClimate/tabular-py), -which is not on PyPI yet, so it is not installed by default: - -``` shell -uv pip install git+https://github.com/dClimate/tabular-py -``` - -Until it is installed, `client.stations` raises `TabularNotInstalledError` with -those instructions. Once `tabular-py` is published it moves into the ordinary -dependency list, matching `dclimate-client-js`. +Station 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: diff --git a/dclimate_client_py/stations/__init__.py b/dclimate_client_py/stations/__init__.py index 5c38560..46a85f8 100644 --- a/dclimate_client_py/stations/__init__.py +++ b/dclimate_client_py/stations/__init__.py @@ -1,8 +1,9 @@ -"""Station (point-observation) dataset support, built on ``tabular-py``. +"""Station (point-observation) dataset support, built on ``tabular_py``. -Everything here imports without ``tabular_py`` installed; the dependency is only -required once a dataset is actually loaded, which is what lets the rest of the -library import cleanly when the optional extra is absent. +``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 station support. """ from .errors import translate_station_error diff --git a/dclimate_client_py/stations/errors.py b/dclimate_client_py/stations/errors.py index c479cc2..1288de4 100644 --- a/dclimate_client_py/stations/errors.py +++ b/dclimate_client_py/stations/errors.py @@ -40,7 +40,8 @@ def translate_station_error(cause: BaseException) -> NoReturn: the station, 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 require the optional dependency. + # 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, diff --git a/dclimate_client_py/stations/stations_client.py b/dclimate_client_py/stations/stations_client.py index 003fd62..3a0265f 100644 --- a/dclimate_client_py/stations/stations_client.py +++ b/dclimate_client_py/stations/stations_client.py @@ -33,18 +33,22 @@ def _require_tabular() -> typing.Any: - """Import ``tabular_py``, or explain how to install it. + """Import ``tabular_py``, or say plainly that it is missing. - Optional only because ``tabular-py`` is not on PyPI yet; the JS client - depends on ``@dclimate/tabular`` unconditionally. + 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( - "Station data requires tabular-py, which is not on PyPI yet. " - "Install it with:\n" - " uv pip install git+https://github.com/dClimate/tabular-py" + "Station 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 diff --git a/pyproject.toml b/pyproject.toml index 77fafd4..8c4e97c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,16 +29,6 @@ classifiers = [ "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [ - # NOTE: station data (`client.stations`) needs `tabular-py`, which is not on - # PyPI yet. It is deliberately *not* declared here or as an extra: uv - # resolves every extra when locking, so naming an unpublished package makes - # even `uv sync` fail for people who never touch station data. Install it - # alongside for now -- - # uv pip install git+https://github.com/dClimate/tabular-py - # -- and move it into this list once it is published, matching - # dclimate-client-js, which depends on @dclimate/tabular unconditionally. - # `client.stations` raises TabularNotInstalledError with these instructions - # until then. "aiobotocore>=2.13.0", "aiohttp>=3.9.0", "xarray>=2025.3.0", @@ -49,6 +39,12 @@ dependencies = [ "numcodecs[crc32c]>=0.14,<0.16", "numpy>=2.1.3", "py_hamt>=3.6.0", + # Station (point-observation) datasets, behind `client.stations`. Imported + # as `tabular_py`; the distribution is namespaced because PyPI normalises + # "tabular-py" onto the unrelated existing "tabularpy" project. Declared + # unconditionally, matching dclimate-client-js's dependency on + # @dclimate/tabular. + "dclimate-tabular-py>=0.1.0", "multiformats>=0.3.1", "geopandas>=1.0.0", "pandas>=2.2.0", diff --git a/tests/test_stations.py b/tests/test_stations.py index ae0b584..ffbd58f 100644 --- a/tests/test_stations.py +++ b/tests/test_stations.py @@ -26,7 +26,7 @@ tabular_py = pytest.importorskip( "tabular_py", - reason="station support needs tabular-py, which is not on PyPI yet", + reason="station support needs the dclimate-tabular-py distribution", ) from tabular_py.errors import ( # noqa: E402 @@ -283,8 +283,8 @@ async def rows(_cause: Exception = cause) -> list[object]: await dataset.rows() -class TestOptionalDependency: - def test_absence_is_reported_with_install_guidance(self, monkeypatch) -> None: +class TestMissingDependency: + def test_absence_names_the_distribution_not_the_module(self, monkeypatch) -> None: import builtins from dclimate_client_py.stations import stations_client @@ -297,5 +297,8 @@ def missing(name: str, *args: object, **kwargs: object) -> object: return real_import(name, *args, **kwargs) monkeypatch.setattr(builtins, "__import__", missing) - with pytest.raises(TabularNotInstalledError, match="tabular-py"): + # 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"): stations_client._require_tabular() diff --git a/uv.lock b/uv.lock index 6390360..82a65dc 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.1.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.1.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/fe/cc/a409e8a1399679cb3798b9276519a673380c62f6f448416189513baaddf6/dclimate_tabular_py-0.1.0.tar.gz", hash = "sha256:930e94f13da793bf5dc317166d33f17b39253dcf81d19898d34269321d28faff", size = 354400, upload-time = "2026-08-13T17:45:02.792Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/37/75/78448edafb885c249540d96e3c28b3b886bf320f153d2c2b5342e6408118/dclimate_tabular_py-0.1.0-py3-none-any.whl", hash = "sha256:b78c55c89fc92302126794487462f6407c9e496aa140945dc12eafe6adb5e052", size = 47776, upload-time = "2026-08-13T17:45:01.352Z" }, +] + [[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" From 8b43c6155d440eac14a6cf21d10a30b04b77a6d9 Mon Sep 17 00:00:00 2001 From: TheGreatAlgo <37487508+TheGreatAlgo@users.noreply.github.com> Date: Thu, 13 Aug 2026 15:12:18 -0400 Subject: [PATCH 3/4] fix: station namespace transport lifecycle Three defects found in review, all about a cached StationsClient outliving the transport it was built for. A KuboCAS never reopens once closed, so __aexit__ now drops the station client rather than only closing it: keeping it would make reads after the context fail on a dead transport instead of falling back to the gateway, as the property documents. Rebuilding the namespace onto the CAS used to discard the previous gateway-backed instance and its open sources. Since the replacement is the only instance __aexit__ closes, those pools leaked; the replacement now adopts them. Building happens in a property, which cannot await, so the sources move rather than being closed there. aclose() stopped at the first failing source, stranding the rest with no way to retry them -- the list is cleared up front. It now closes every source and re-raises the first failure afterwards. Each test fails on the previous commit and passes here. --- dclimate_client_py/dclimate_client.py | 22 +++-- .../stations/stations_client.py | 26 +++++- tests/test_stations.py | 82 +++++++++++++++++++ 3 files changed, 124 insertions(+), 6 deletions(-) diff --git a/dclimate_client_py/dclimate_client.py b/dclimate_client_py/dclimate_client.py index 3512931..ed5b794 100644 --- a/dclimate_client_py/dclimate_client.py +++ b/dclimate_client_py/dclimate_client.py @@ -227,6 +227,13 @@ async def __aexit__(self, exc_type, exc_val, exc_tb): await self._stations_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 station reads after the context fail on a dead transport + # instead of falling back to the gateway, which is what the + # `stations` property promises outside the context. + self._stations_client = None try: if self._kubo_cas is not None: @@ -878,14 +885,19 @@ def stations(self) -> StationsClient: was first created before ``__aenter__``. """ cas = self._kubo_cas - if self._stations_client is None or ( - cas is not None and self._stations_client._cas is not cas - ): - self._stations_client = StationsClient( + current = self._stations_client + if current is None or current._cas is not cas: + replacement = StationsClient( gateway_url=self._catalog_gateway_base_url, cas=cas, ) - return self._stations_client + 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._stations_client = replacement + return current # ------------------------------------------------------------------ # Siren REST API methods diff --git a/dclimate_client_py/stations/stations_client.py b/dclimate_client_py/stations/stations_client.py index 3a0265f..21ead0f 100644 --- a/dclimate_client_py/stations/stations_client.py +++ b/dclimate_client_py/stations/stations_client.py @@ -71,6 +71,18 @@ def __init__( self._cas = cas self._owned_sources: list[typing.Any] = [] + def _adopt_sources_from(self, other: StationsClient) -> 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 @@ -170,7 +182,19 @@ async def aclose(self) -> None: 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: - await source.aclose() + try: + await source.aclose() + except BaseException as error: + if failure is None: + failure = error + if failure is not None: + raise failure diff --git a/tests/test_stations.py b/tests/test_stations.py index ffbd58f..bde188d 100644 --- a/tests/test_stations.py +++ b/tests/test_stations.py @@ -126,6 +126,88 @@ def test_a_gateway_override_bypasses_the_cas(self) -> None: 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 station 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.stations + assert during._cas is client._kubo_cas + + await client.__aexit__(None, None, None) + + assert client._stations_client is None + after = client.stations + assert after is not during + assert after._cas is None + + async def test_rebuilding_onto_the_cas_does_not_strand_gateway_sources( + self, + ) -> None: + # Station 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.stations + source = Source() + before._owned_sources.append(source) + + client._kubo_cas = FakeCas() # type: ignore[assignment] + after = client.stations + 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) + + stations = StationsClient(gateway_url="https://unused.example") + stations._owned_sources.extend( + [Source("first"), Source("second", fails=True), Source("third")] + ) + + with pytest.raises(RuntimeError, match="second refused to close"): + await stations.aclose() + + # The failure is reported, but not at the cost of the healthy pools. + assert closed == ["first", "third"] + assert stations._owned_sources == [] + + class TestTranslateStationError: """The mapping, by who has to act.""" From 7fe4bd69556562b37dc2f48f7d278c37e6c91907 Mon Sep 17 00:00:00 2001 From: TheGreatAlgo <37487508+TheGreatAlgo@users.noreply.github.com> Date: Wed, 26 Aug 2026 12:08:08 -0400 Subject: [PATCH 4/4] fix: entity sync --- README.md | 71 ++++-- dclimate_client_py/__init__.py | 10 +- dclimate_client_py/dclimate_client.py | 32 +-- dclimate_client_py/dclimate_zarr_errors.py | 2 +- dclimate_client_py/entities/__init__.py | 22 ++ .../entities_client.py} | 90 ++++--- .../{stations => entities}/errors.py | 16 +- .../{stations => entities}/wrap.py | 36 +-- dclimate_client_py/stations/__init__.py | 18 -- pyproject.toml | 7 +- tests/helpers/__init__.py | 1 + tests/helpers/entity_fixture.py | 241 ++++++++++++++++++ tests/{test_stations.py => test_entities.py} | 231 ++++++++++++----- uv.lock | 8 +- 14 files changed, 587 insertions(+), 198 deletions(-) create mode 100644 dclimate_client_py/entities/__init__.py rename dclimate_client_py/{stations/stations_client.py => entities/entities_client.py} (65%) rename dclimate_client_py/{stations => entities}/errors.py (90%) rename dclimate_client_py/{stations => entities}/wrap.py (76%) delete mode 100644 dclimate_client_py/stations/__init__.py create mode 100644 tests/helpers/__init__.py create mode 100644 tests/helpers/entity_fixture.py rename tests/{test_stations.py => test_entities.py} (58%) diff --git a/README.md b/README.md index a1bdbf5..b8b93c5 100644 --- a/README.md +++ b/README.md @@ -227,13 +227,18 @@ 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. -## Station data usage +## Entity data usage -Gridded Zarr datasets come from `load_dataset`. Point-observation **station** -datasets (GHCND and friends) live under `client.stations`, and read the same way: +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. -Station support is built on +"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 @@ -241,15 +246,15 @@ unrelated existing project. ```python async with dClimateClient() as client: - stations = await client.stations.load("bafyr4i...") + ghcnd = await client.entities.load("bafyr4i...") - # Every station, with position and coverage window. - for s in await stations.list_stations(): - print(s.station_id, s.latitude, s.longitude, s.start, s.end) + # 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) - # Stations within 50 km of a point, over one week. + # Entities within 50 km of a point, over one week. records = await ( - stations + ghcnd .circle(40.75, -73.99, 50) .time_range("2023-01-01", "2023-01-07") .to_records("TMAX") @@ -257,13 +262,39 @@ async with dClimateClient() as client: ``` Reads go through the client's own IPFS transport, so pinning, retries, and -configured endpoints apply to station reads too. Resolution is by CID for now; +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 = stations.time_range("2023-01-01", "2023-01-07") +week = ghcnd.time_range("2023-01-01", "2023-01-07") nyc = await week.select("USW00094728").rows() lax = await week.select("USW00023174").rows() ``` @@ -271,7 +302,7 @@ 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; stations are irregular, so the nearest one may + 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: @@ -279,35 +310,35 @@ Two things differ from `GeotemporalData`, because the data model differs: ```python from tabular_py import gt -# `nearest` reads the station index to find the match, so it is awaited -- +# `nearest` reads the entity index to find the match, so it is awaited -- # unlike the synchronous selections above. hot_days = await ( - (await stations.nearest(29.98, -95.36)) + (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 *station*, which is not always the nearest +`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 station in one call. -station = await client.stations.nearest( +# 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(station.station_id, station.km) +print(nearest.entity_id, nearest.km) ``` -Station failures arrive as this library's own errors, for the whole chain rather +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 diff --git a/dclimate_client_py/__init__.py b/dclimate_client_py/__init__.py index 76d99fa..86d7a90 100644 --- a/dclimate_client_py/__init__.py +++ b/dclimate_client_py/__init__.py @@ -54,8 +54,8 @@ "dClimateClient": (".dclimate_client", "dClimateClient"), "GeotemporalData": (".geotemporal_data", "GeotemporalData"), "load_stac_catalog": (".stac_catalog", "load_stac_catalog"), - "StationsClient": (".stations", "StationsClient"), - "WrappedStationDataset": (".stations", "WrappedStationDataset"), + "EntitiesClient": (".entities", "EntitiesClient"), + "WrappedEntityDataset": (".entities", "WrappedEntityDataset"), "list_available_datasets": (".stac_catalog", "list_available_datasets"), } @@ -118,8 +118,8 @@ def __dir__() -> list[str]: "SirenApiError", "X402PaymentError", "X402NotInstalledError", - # Stations - "StationsClient", - "WrappedStationDataset", + # Entities + "EntitiesClient", + "WrappedEntityDataset", "TabularNotInstalledError", ] diff --git a/dclimate_client_py/dclimate_client.py b/dclimate_client_py/dclimate_client.py index ed5b794..d8b82f2 100644 --- a/dclimate_client_py/dclimate_client.py +++ b/dclimate_client_py/dclimate_client.py @@ -40,7 +40,7 @@ list_versions_from_url, ) from .siren import SirenClient -from .stations import StationsClient +from .entities import EntitiesClient from .siren.types import ( SirenMetricDataPoint, SirenMetricQuery, @@ -171,9 +171,9 @@ def __init__( if siren is not None: self._siren_client = SirenClient(siren) - # Station datasets. Unlike Siren this needs no configuration, so it is - # built on first access rather than here -- see the `stations` property. - self._stations_client: typing.Optional["StationsClient"] = None + # 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.""" @@ -223,17 +223,17 @@ async def __aexit__(self, exc_type, exc_val, exc_tb): cleanup_error = _merge_cleanup_error(cleanup_error, error) try: - if self._stations_client is not None: - await self._stations_client.aclose() + 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 station reads after the context fail on a dead transport + # make entity reads after the context fail on a dead transport # instead of falling back to the gateway, which is what the - # `stations` property promises outside the context. - self._stations_client = None + # `entities` property promises outside the context. + self._entities_client = None try: if self._kubo_cas is not None: @@ -867,27 +867,27 @@ async def get_dataset_version( ) # ------------------------------------------------------------------ - # Station (point-observation) datasets + # Entity (point-observation) datasets # ------------------------------------------------------------------ @property - def stations(self) -> StationsClient: - """Station datasets, e.g. ``await client.stations.load(cid)``. + 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 station reads too. + 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._stations_client + current = self._entities_client if current is None or current._cas is not cas: - replacement = StationsClient( + replacement = EntitiesClient( gateway_url=self._catalog_gateway_base_url, cas=cas, ) @@ -896,7 +896,7 @@ def stations(self) -> StationsClient: # opened. It is the only one `__aexit__` closes, so without this # those connection pools would leak. replacement._adopt_sources_from(current) - current = self._stations_client = replacement + current = self._entities_client = replacement return current # ------------------------------------------------------------------ diff --git a/dclimate_client_py/dclimate_zarr_errors.py b/dclimate_client_py/dclimate_zarr_errors.py index 33bd54d..eb9fb44 100644 --- a/dclimate_client_py/dclimate_zarr_errors.py +++ b/dclimate_client_py/dclimate_zarr_errors.py @@ -127,4 +127,4 @@ class X402NotInstalledError(ZarrClientError): class TabularNotInstalledError(ZarrClientError): - """Raised when station data is requested but tabular-py is not installed""" + """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/stations/stations_client.py b/dclimate_client_py/entities/entities_client.py similarity index 65% rename from dclimate_client_py/stations/stations_client.py rename to dclimate_client_py/entities/entities_client.py index 21ead0f..7c5599d 100644 --- a/dclimate_client_py/stations/stations_client.py +++ b/dclimate_client_py/entities/entities_client.py @@ -1,14 +1,18 @@ -"""Station (point-observation) datasets, as opposed to the gridded Zarr datasets. +"""Entity (point-observation) datasets, as opposed to the gridded Zarr datasets. -Mirrors ``dclimate-client-js`` ``src/stations/stations-client.ts``. +Mirrors ``dclimate-client-js`` ``src/entities/entities-client.ts``. -The two are different enough underneath -- irregular stations with per-station +"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. ``StationDataset`` provides that surface, so +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 station data +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. """ @@ -21,15 +25,17 @@ DatasetNotFoundError, TabularNotInstalledError, ) -from .errors import translate_station_error -from .wrap import WrappedStationDataset, wrap_station_dataset +from .errors import translate_entity_error +from .wrap import WrappedEntityDataset, wrap_entity_dataset if typing.TYPE_CHECKING: # pragma: no cover - from collections.abc import Sequence + from collections.abc import Callable, Sequence from py_hamt import KuboCAS - from tabular_py import NearestStation - from tabular_py.station_dataset import TimeInput + from tabular_py import NearestEntity, TableField + from tabular_py.entity_dataset import TimeInput + + ColumnKey = Callable[[TableField], str] def _require_tabular() -> typing.Any: @@ -45,7 +51,7 @@ def _require_tabular() -> typing.Any: import tabular_py except ImportError as cause: raise TabularNotInstalledError( - "Station data requires the `tabular_py` module, which ships in the " + "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" @@ -53,8 +59,8 @@ def _require_tabular() -> typing.Any: return tabular_py -class StationsClient: - """Loads station datasets by CID. +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 @@ -71,7 +77,7 @@ def __init__( self._cas = cas self._owned_sources: list[typing.Any] = [] - def _adopt_sources_from(self, other: StationsClient) -> None: + 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 @@ -100,14 +106,24 @@ async def load( cid: str, *, gateway_url: str | None = None, - ) -> WrappedStationDataset: - """Open a station dataset by root CID. + 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( - "A station dataset CID is required. Catalog resolution is not " + "An entity dataset CID is required. Catalog resolution is not " "available yet." ) @@ -120,6 +136,9 @@ async def load( 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 @@ -130,9 +149,11 @@ async def load( # tabular's errors too, and a caller has no reason to expect the boundary # to stop at `open`. try: - return wrap_station_dataset(await tabular.StationDataset.open(source, root)) + return wrap_entity_dataset( + await tabular.EntityDataset.open(source, root, **mapping) + ) except BaseException as cause: - translate_station_error(cause) + translate_entity_error(cause) async def nearest( self, @@ -144,31 +165,36 @@ async def nearest( max_km: float | None = None, within: tuple[TimeInput, TimeInput] | None = None, gateway_url: str | None = None, - ) -> NearestStation: - """The station nearest a point that actually has the data you asked for. + column_key: ColumnKey | None = None, + ) -> NearestEntity: + """The entity nearest a point that actually has the data you asked for. - Resolves the dataset and the station in one call, because "which station - should I use for this location" is the question most callers open a - station dataset to ask, and answering it through :meth:`load` means + 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 stations that actually report every - one of those columns. Without it, "nearest" means nearest *station*, not + ``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 station reported the + 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. - Returns the distance alongside the station: a dataset with no coverage - near the queried point still has a nearest station, and the only way to + ``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) + 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( - "NearestStation", - await dataset.find_nearest_station( + "NearestEntity", + await dataset.find_nearest_entity( latitude, longitude, max_km=max_km, diff --git a/dclimate_client_py/stations/errors.py b/dclimate_client_py/entities/errors.py similarity index 90% rename from dclimate_client_py/stations/errors.py rename to dclimate_client_py/entities/errors.py index 1288de4..4892b52 100644 --- a/dclimate_client_py/stations/errors.py +++ b/dclimate_client_py/entities/errors.py @@ -1,10 +1,10 @@ """Translating ``tabular-py`` failures into this library's error types. -Mirrors ``dclimate-client-js`` ``src/stations/errors.ts``. +Mirrors ``dclimate-client-js`` ``src/entities/errors.ts``. -Station queries are answered by ``tabular_py``, whose errors descend from its own +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 station +``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. """ @@ -20,8 +20,8 @@ ) -def translate_station_error(cause: BaseException) -> NoReturn: - """Re-raise a station query failure as this library's own error type. +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 @@ -37,7 +37,7 @@ def translate_station_error(cause: BaseException) -> NoReturn: dataset. The original message is preserved verbatim: it is the only part that names - the station, column, or distance that actually failed. + 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 @@ -48,10 +48,10 @@ def translate_station_error(cause: BaseException) -> NoReturn: DclimateTabularError, PredicateError, RangeSourceError, - StationSelectionError, + EntitySelectionError, ) - if isinstance(cause, StationSelectionError): + if isinstance(cause, EntitySelectionError): if cause.reason == "not-found": raise NoDataFoundError(str(cause)) from cause raise InvalidSelectionError(str(cause)) from cause diff --git a/dclimate_client_py/stations/wrap.py b/dclimate_client_py/entities/wrap.py similarity index 76% rename from dclimate_client_py/stations/wrap.py rename to dclimate_client_py/entities/wrap.py index 13c41db..5f0e6fe 100644 --- a/dclimate_client_py/stations/wrap.py +++ b/dclimate_client_py/entities/wrap.py @@ -1,18 +1,18 @@ """Keeping the error boundary closed across a whole selection chain. -Mirrors ``dclimate-client-js`` ``src/stations/wrap.ts``, which uses a ``Proxy`` +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 station, ``where`` on a non-comparable column, or +``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* ``StationDataset`` instances, so a class would +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 @@ -21,9 +21,9 @@ Three return shapes are handled, because the API has all three: -* sync chainable (``select``, ``time_range``, ``where``) -> re-wrap +* sync chainable (``select``, ``time_range``, ``where``, ``circle``) -> re-wrap * async chainable (``nearest``) -> re-wrap on await -* async terminal (``rows``, ``plan``, ``list_stations``) -> translate the raise +* async terminal (``rows``, ``plan``, ``list_entities``) -> translate the raise """ from __future__ import annotations @@ -32,14 +32,14 @@ import inspect from typing import TYPE_CHECKING, Any -from .errors import translate_station_error +from .errors import translate_entity_error if TYPE_CHECKING: # pragma: no cover - from tabular_py import StationDataset + from tabular_py import EntityDataset -class WrappedStationDataset: - """A :class:`~tabular_py.StationDataset` whose every failure is this library's. +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 @@ -48,11 +48,11 @@ class WrappedStationDataset: __slots__ = ("_dataset",) - def __init__(self, dataset: StationDataset) -> None: + def __init__(self, dataset: EntityDataset) -> None: object.__setattr__(self, "_dataset", dataset) @property - def unwrapped(self) -> StationDataset: + 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] @@ -70,7 +70,7 @@ def call(*args: Any, **kwargs: Any) -> Any: except BaseException as cause: # A synchronous raise -- an unknown column rejected at selection # time, before any I/O. - translate_station_error(cause) + translate_entity_error(cause) if inspect.isawaitable(result): return _awaited(result) return _rewrap(result) @@ -85,20 +85,20 @@ async def _awaited(awaitable: Any) -> Any: try: resolved = await awaitable except BaseException as cause: - translate_station_error(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 StationDataset + from tabular_py import EntityDataset - if isinstance(value, StationDataset): - return WrappedStationDataset(value) + if isinstance(value, EntityDataset): + return WrappedEntityDataset(value) return value -def wrap_station_dataset(dataset: StationDataset) -> WrappedStationDataset: +def wrap_entity_dataset(dataset: EntityDataset) -> WrappedEntityDataset: """Wrap a dataset so every method failure comes back as a ``ZarrClientError``.""" - return WrappedStationDataset(dataset) + return WrappedEntityDataset(dataset) diff --git a/dclimate_client_py/stations/__init__.py b/dclimate_client_py/stations/__init__.py deleted file mode 100644 index 46a85f8..0000000 --- a/dclimate_client_py/stations/__init__.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Station (point-observation) dataset support, built on ``tabular_py``. - -``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 station support. -""" - -from .errors import translate_station_error -from .stations_client import StationsClient -from .wrap import WrappedStationDataset, wrap_station_dataset - -__all__ = [ - "StationsClient", - "WrappedStationDataset", - "translate_station_error", - "wrap_station_dataset", -] diff --git a/pyproject.toml b/pyproject.toml index 8c4e97c..83f3eb2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,12 +39,7 @@ dependencies = [ "numcodecs[crc32c]>=0.14,<0.16", "numpy>=2.1.3", "py_hamt>=3.6.0", - # Station (point-observation) datasets, behind `client.stations`. Imported - # as `tabular_py`; the distribution is namespaced because PyPI normalises - # "tabular-py" onto the unrelated existing "tabularpy" project. Declared - # unconditionally, matching dclimate-client-js's dependency on - # @dclimate/tabular. - "dclimate-tabular-py>=0.1.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_stations.py b/tests/test_entities.py similarity index 58% rename from tests/test_stations.py rename to tests/test_entities.py index bde188d..5f4d5b6 100644 --- a/tests/test_stations.py +++ b/tests/test_entities.py @@ -1,7 +1,7 @@ -"""Station dataset support: the client namespace and the error boundary. +"""Entity dataset support: the client namespace and the error boundary. -Mirrors ``dclimate-client-js`` ``tests/stations.test.ts`` and -``tests/stations-wrap.test.ts``. +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 @@ -22,11 +22,11 @@ ZarrClientError, ) from dclimate_client_py.dclimate_client import dClimateClient -from dclimate_client_py.stations import StationsClient +from dclimate_client_py.entities import EntitiesClient tabular_py = pytest.importorskip( "tabular_py", - reason="station support needs the dclimate-tabular-py distribution", + reason="entity support needs the dclimate-tabular-py distribution", ) from tabular_py.errors import ( # noqa: E402 @@ -35,26 +35,23 @@ DatasetReaderError, PredicateError, RangeSourceError, - StationSelectionError, + EntitySelectionError, WireError, ) -from dclimate_client_py.stations.errors import translate_station_error # noqa: E402 -from dclimate_client_py.stations.wrap import wrap_station_dataset # noqa: E402 +from dclimate_client_py.entities.errors import translate_entity_error # noqa: E402 +from dclimate_client_py.entities.wrap import wrap_entity_dataset # noqa: E402 -# A real, published GHCND station dataset. -REAL_CID = "bafyr4if2wbttslbxpzmro427j4l4nvcrxqo4tufuffqqmqz7afj2pxyu4a" - -def fake(**overrides: object) -> tabular_py.StationDataset: +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 - ``StationDataset`` instance so the wrapper's ``isinstance`` re-wrapping check + ``EntityDataset`` instance so the wrapper's ``isinstance`` re-wrapping check sees what it would see in production. """ - dataset = object.__new__(tabular_py.StationDataset) + dataset = object.__new__(tabular_py.EntityDataset) for name, value in overrides.items(): object.__setattr__(dataset, name, value) return dataset @@ -62,15 +59,15 @@ def fake(**overrides: object) -> tabular_py.StationDataset: class TestClientNamespace: def test_available_without_configuration(self) -> None: - # Siren needs credentials and raises when unconfigured; station reads + # 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.stations, StationsClient) + assert isinstance(client.entities, EntitiesClient) def test_reuses_one_instance_across_accesses(self) -> None: client = dClimateClient() - assert client.stations is client.stations + assert client.entities is client.entities async def test_rejects_a_malformed_cid_before_touching_the_network(self) -> None: calls: list[str] = [] @@ -84,11 +81,11 @@ async def get_range(self, cid: object, offset: int, length: int) -> bytes: calls.append("get_range") raise AssertionError("should not be reached") - stations = StationsClient(gateway_url="http://127.0.0.1:8080") - stations._source = lambda _gateway: Recording() # type: ignore[method-assign] + entities = EntitiesClient(gateway_url="http://127.0.0.1:8080") + entities._source = lambda _gateway: Recording() # type: ignore[method-assign] with pytest.raises(DatasetNotFoundError): - await stations.load("obviously-not-a-cid") + 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 == [] @@ -96,33 +93,33 @@ async def get_range(self, cid: object, offset: int, length: int) -> bytes: async def test_requires_a_cid_until_catalog_resolution_exists(self) -> None: client = dClimateClient() with pytest.raises(DatasetNotFoundError): - await client.stations.load("") + await client.entities.load("") async def test_routes_reads_through_the_gateway_it_was_given(self) -> None: - stations = StationsClient(gateway_url="https://gateway.example") - source = stations._source(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 stations.aclose() + await entities.aclose() async def test_a_per_request_gateway_overrides_the_client_default(self) -> None: - stations = StationsClient(gateway_url="https://default.example") - source = stations._source("https://override.example") + entities = EntitiesClient(gateway_url="https://default.example") + source = entities._source("https://override.example") assert "override.example" in repr(source.__dict__) - await stations.aclose() + await entities.aclose() def test_prefers_the_clients_own_cas_when_open(self) -> None: sentinel = object() - stations = StationsClient(gateway_url="https://unused.example", cas=sentinel) - source = stations._source(None) + 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: - stations = StationsClient(gateway_url="https://default.example", cas=object()) - source = stations._source("https://override.example") + entities = EntitiesClient(gateway_url="https://default.example", cas=object()) + source = entities._source("https://override.example") assert isinstance(source, tabular_py.GatewayRangeSource) @@ -140,24 +137,24 @@ 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 station reads after the context fail on a dead + # 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.stations + during = client.entities assert during._cas is client._kubo_cas await client.__aexit__(None, None, None) - assert client._stations_client is None - after = client.stations + 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: - # Station data loaded before __aenter__ opens a gateway source. The + # 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] = [] @@ -167,12 +164,12 @@ async def aclose(self) -> None: closed.append(self) client = dClimateClient() - before = client.stations + before = client.entities source = Source() before._owned_sources.append(source) client._kubo_cas = FakeCas() # type: ignore[assignment] - after = client.stations + after = client.entities assert after is not before assert before._owned_sources == [] assert after._owned_sources == [source] @@ -195,38 +192,38 @@ async def aclose(self) -> None: raise RuntimeError(f"{self.name} refused to close") closed.append(self.name) - stations = StationsClient(gateway_url="https://unused.example") - stations._owned_sources.extend( + 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 stations.aclose() + await entities.aclose() # The failure is reported, but not at the cost of the healthy pools. assert closed == ["first", "third"] - assert stations._owned_sources == [] + assert entities._owned_sources == [] -class TestTranslateStationError: +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_station_error(StationSelectionError("no match", "not-found")) + translate_entity_error(EntitySelectionError("no match", "not-found")) def test_invalid_selection_becomes_invalid_selection(self) -> None: with pytest.raises(InvalidSelectionError): - translate_station_error(StationSelectionError("bad", "invalid")) + 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_station_error(DatasetIntegrityError("bad digest")) + translate_entity_error(DatasetIntegrityError("bad digest")) @pytest.mark.parametrize( "cause", @@ -236,7 +233,7 @@ def test_reader_and_predicate_failures_are_invalid_selections( self, cause: Exception ) -> None: with pytest.raises(InvalidSelectionError): - translate_station_error(cause) + translate_entity_error(cause) def test_transport_failures_pass_through_untranslated(self) -> None: # A gateway timeout is retryable and says nothing about the dataset; @@ -244,7 +241,7 @@ def test_transport_failures_pass_through_untranslated(self) -> None: # what is usually a network blip. original = RangeSourceError("gateway 503") with pytest.raises(RangeSourceError) as raised: - translate_station_error(original) + translate_entity_error(original) assert raised.value is original @pytest.mark.parametrize( @@ -254,7 +251,7 @@ 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_station_error(cause) + translate_entity_error(cause) # The specific class stays visible even though the branch is generic. assert type(cause).__name__ in str(raised.value) @@ -262,17 +259,17 @@ 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_station_error(original) + 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 station, column, or distance + # 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_station_error(DatasetReaderError("column 'TMPX' at row 12")) + translate_entity_error(DatasetReaderError("column 'TMPX' at row 12")) -class TestWrapStationDataset: +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: @@ -281,15 +278,15 @@ async def test_translates_a_rejection_from_a_terminal_method(self) -> None: async def rows() -> list[object]: raise DatasetReaderError("unknown column") - dataset = wrap_station_dataset(fake(rows=rows)) + 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 StationSelectionError("no match", "not-found") + raise EntitySelectionError("no match", "not-found") - dataset = wrap_station_dataset(fake(rows=rows)) + dataset = wrap_entity_dataset(fake(rows=rows)) with pytest.raises(NoDataFoundError): await dataset.rows() @@ -298,7 +295,7 @@ def test_translates_a_synchronous_raise_from_a_selector(self) -> None: def elements(*names: str) -> object: raise DatasetReaderError("unknown element") - dataset = wrap_station_dataset(fake(elements=elements)) + dataset = wrap_entity_dataset(fake(elements=elements)) with pytest.raises(InvalidSelectionError): dataset.elements("TMPX") @@ -307,11 +304,11 @@ async def rows() -> list[object]: raise DatasetReaderError("late failure") inner = fake(rows=rows) - dataset = wrap_station_dataset(fake(select=lambda *ids: inner)) + 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__ == "WrappedStationDataset" + assert type(selected).__name__ == "WrappedEntityDataset" async def test_rewraps_an_async_chainable(self) -> None: async def rows() -> list[object]: @@ -322,37 +319,37 @@ async def rows() -> list[object]: async def nearest(*args: object, **kwargs: object) -> object: return inner - dataset = wrap_station_dataset(fake(nearest=nearest)) + dataset = wrap_entity_dataset(fake(nearest=nearest)) selected = await dataset.nearest(34.0, -118.0) - assert type(selected).__name__ == "WrappedStationDataset" + assert type(selected).__name__ == "WrappedEntityDataset" with pytest.raises(InvalidSelectionError): await selected.rows() async def test_passes_plain_data_through_untouched(self) -> None: - payload = [{"station_id": "USW00023174", "value": 3}] + payload = [{"entity_id": "USW00023174", "value": 3}] async def rows() -> list[object]: return payload - dataset = wrap_station_dataset(fake(rows=rows)) + 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_station_dataset(fake(_query="a-query")) + 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_station_dataset(inner).unwrapped is inner + 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 station failures too. + # around the client catches entity failures too. for cause in ( DatasetReaderError("bad"), - StationSelectionError("gone", "not-found"), + EntitySelectionError("gone", "not-found"), DatasetIntegrityError("corrupt"), WireError("not a root"), ): @@ -360,7 +357,7 @@ async def test_every_escaping_error_is_this_librarys(self) -> None: async def rows(_cause: Exception = cause) -> list[object]: raise _cause - dataset = wrap_station_dataset(fake(rows=rows)) + dataset = wrap_entity_dataset(fake(rows=rows)) with pytest.raises(ZarrClientError): await dataset.rows() @@ -369,7 +366,7 @@ class TestMissingDependency: def test_absence_names_the_distribution_not_the_module(self, monkeypatch) -> None: import builtins - from dclimate_client_py.stations import stations_client + from dclimate_client_py.entities import entities_client real_import = builtins.__import__ @@ -383,4 +380,98 @@ def missing(name: str, *args: object, **kwargs: object) -> object: # 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"): - stations_client._require_tabular() + 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 82a65dc..e46f0e9 100644 --- a/uv.lock +++ b/uv.lock @@ -722,7 +722,7 @@ testing = [ requires-dist = [ { name = "aiobotocore", specifier = ">=2.13.0" }, { name = "aiohttp", specifier = ">=3.9.0" }, - { name = "dclimate-tabular-py", specifier = ">=0.1.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" }, @@ -753,7 +753,7 @@ provides-extras = ["testing", "dev", "examples"] [[package]] name = "dclimate-tabular-py" -version = "0.1.0" +version = "0.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "blake3" }, @@ -763,9 +763,9 @@ dependencies = [ { name = "py-hamt" }, { name = "pyarrow" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/fe/cc/a409e8a1399679cb3798b9276519a673380c62f6f448416189513baaddf6/dclimate_tabular_py-0.1.0.tar.gz", hash = "sha256:930e94f13da793bf5dc317166d33f17b39253dcf81d19898d34269321d28faff", size = 354400, upload-time = "2026-08-13T17:45:02.792Z" } +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/37/75/78448edafb885c249540d96e3c28b3b886bf320f153d2c2b5342e6408118/dclimate_tabular_py-0.1.0-py3-none-any.whl", hash = "sha256:b78c55c89fc92302126794487462f6407c9e496aa140945dc12eafe6adb5e052", size = 47776, upload-time = "2026-08-13T17:45:01.352Z" }, + { 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]]