Skip to content

feat(waterdata): add waterdata.bulk, getters for the nightly Parquet files - #479

Draft
thodson-usgs wants to merge 4 commits into
DOI-USGS:mainfrom
thodson-usgs:feat/waterdata-bulk
Draft

thodson-usgs wants to merge 4 commits into
DOI-USGS:mainfrom
thodson-usgs:feat/waterdata-bulk

Conversation

@thodson-usgs

@thodson-usgs thodson-usgs commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

USGS publishes the daily and continuous collections as Parquet files, one set per monitoring location, written each night and indexed by the Water Data STAC catalog (announcement). This PR adds waterdata.bulk, three getters that read them. waterdata.get_daily and waterdata.get_continuous do not change.

This is the first part of #476, split from it so that it can ship in a 1.x release. #476 keeps the bulk setting, which sends a large get_daily or get_continuous query to these getters, and ADR 0014.

waterdata/
├── catalog.py         # the one STAC search; get_ratings uses it too
└── bulk/              # imports neither time_series nor api (.importlinter)
    ├── __init__.py    # get_daily, get_continuous, get_urls
    ├── _getters.py    # signatures: only the arguments the files can answer
    ├── _retrieval.py  # parse(args) -> Query, read(Query) -> (df, md)
    └── _urls.py       # get_urls
read(query)
  1 catalog.search(ids)           ids split so each URL is <= 2,094 characters  -> /stac/v0/search
  2 FanOut, one chunk per file    current, historical; rows filtered while read  -> /stac-files/...
      T[location] = newest last_modified in its current file, floored to the day
  3 get_ogc_data(change query)    one OR clause per cutoff day and group of locations,
                                  plus the whole query for locations without a file;
                                  up to 8 chunks, then 10 locations each, at most
                                  the concurrency cap; daily sends no time          -> /ogcapi/...
  4 merge                         the API copy of a (time_series_id, time) replaces the file copy

Steps 3 and 4 run as the downloads' finalize hook, so exc.call.resume() after an interruption returns the whole result.

from dataretrieval.waterdata import bulk

df, md = bulk.get_continuous(sites, parameter_code="00060", time="2025-07-01/..")
urls, md = bulk.get_urls("daily", filter="state_code = '39'")

The bulk getters take only monitoring_location_id (required), parameter_code, statistic_id, time_series_id, approval_status, unit_of_measure, method_category (get_continuous), time and skip_geometry. Any other argument is a TypeError. A get_continuous time may span more than the 1,100 days the API accepts. Without time, they return the full period of record. Without pyarrow, they raise ImportError before any request. The result has the columns and types of the API getter, except daily_id / continuous_id, which the files do not include.

Also in this PR:

  • waterdata.catalog.search is the one catalog search, and the only code that sizes a URL for the catalog's 2,094-character limit. get_ratings uses it, so a long monitoring_location_id list is split across concurrent searches instead of failing with HTTP 403. The search stays scoped to the ratings collection (fix(waterdata): scope the ratings catalog search to its collection #474).
  • stac_api_key (STAC_USGS_PAT, the variable R dataRetrieval reads) is a second Water Data key, sent with every request under /stac-files/ and /stac/, including those of get_ratings. USGS counts requests per key, with hourly ceilings of 1,000 (OGC API), 4,000 (catalog) and 10,000 (files). The change query runs last, so a pull of about 1,000 files under one key leaves it no requests. Without the setting, both use api_key. md.header reports the quota of the key the change query was sent. With api_key set and no STAC key, the first catalog search or file download prints a one-time pointer to set one.
  • dataretrieval[pyarrow] is a new optional extra, included in [test].
  • The OGC engine gains request_url, so the bulk getters' md.url is the URL the API getter sends, and a per-call chunks= for the change query's fan-out.
  • On pandas 3, a text column of the waterdata OGC getters and ngwmn has the same type however the result was paged. Before, a column such as method_category was object when one page had only nulls in it.

Open, from the review of #476 (details there):

  • A historical asset missing from the catalog would drop that history without an error. Not observed.

  • A revision to an old continuous record is read only if USGS rewrites historical after the record changes, which is the rule observed on 2026-11-23.

  • A record deleted from the API since the files were written is returned until the next files (documented).

  • A parameter_code list takes part of the change query's fan-out from the clause split. Not measured.

  • When a location's current and historical files both hold a record, the one with the newest last_modified is kept, whatever order the files were read in. get_urls documents this rule for readers of the files, and its DuckDB example scopes the secret to api.waterdata.usgs.gov.

Evidence

  • Before (main, 67ff6f1): waterdata.bulk does not exist, and get_ratings sends every id in one search URL, so about 60 OH015-... ids exceed 2,094 characters and get HTTP 403.
    After (23a6146): test_many_long_ids_are_split_across_searches_that_fit_the_edge, test_ratings_with_many_ids_are_chunked and the tests in tests/waterdata_bulk_test.py and tests/waterdata_bulk_urls_test.py pass. test_a_bulk_getter_takes_only_the_arguments_the_files_can_answer pins each signature to the arguments the files can answer.
  • On bff9d12, with pyarrow and geopandas installed: 1,762 tests pass offline, and coverage is 99.02%. ruff, ruff format, mypy (strict), lint-imports (8 contracts kept), xenon and complexipy pass. test_overlapping_files_keep_the_newest_last_modified pins the merge rule for both file orders.
  • On 23a6146, with pyarrow and geopandas installed: 1,754 tests pass offline, and coverage is 99.02% (the ratchet is 98.9). The live test_live_bulk_matches_the_api passes for both collections (2026-12-01). A column null in every row, such as method_category at USGS-01435000 since 2026-10-01, is object from the API getter and keeps the files' type from the bulk getter, so the test compares types only for columns with a value. Ruff, ruff format, mypy (strict), lint-imports (8 contracts kept), xenon, complexipy and pre-commit pass.
  • Live, measured on feat(waterdata)!: a cloud-optimized architecture that routes query chunks to the STAC files or the OGC API #476 and not rerun on this branch: 40 Ohio gages' full daily record took 39.8 s from the API and 10.6 s from the files, and 100 gages' whole daily record took 304.5 s and 9.7 s (2026-11-22). Cold on 2026-11-24, rows, values, columns and types matched the API getter in every daily query shape compared (5 shapes).

Merge Danger

Door: two-way. The getters, the catalog module, the extra and the setting are new, and no existing call changes its arguments or its result columns.

Blast Radius: small.

get_ratings now sends its search through catalog.search, as several concurrent requests for a long id list. On pandas 3, an OGC text column that was object because one page had only nulls is now str. show_configuration has a new stac_api_key row. Re-date the NEWS entries to the merge date.

🤖 Generated with Claude Code

thodson-usgs and others added 3 commits December 1, 2026 15:19
…files

USGS publishes the daily and continuous collections as Parquet files, one
set per monitoring location, written each night and indexed by the Water
Data STAC catalog. waterdata.bulk.get_daily() and get_continuous() read a
query's history from the files, and only the records changed since from the
API, and return the columns and types of waterdata.get_daily() and
get_continuous(), except the record id. waterdata.bulk.get_urls() lists the
files and downloads nothing. waterdata.get_daily() and get_continuous() do
not change.

Also in this commit:

- waterdata.catalog is the one STAC search. get_ratings() uses it, so a long
  monitoring_location_id list is split under the catalog's 2,094-character
  URL limit instead of failing with HTTP 403. The search stays scoped to
  the ratings collection (DOI-USGS#474).
- files_api_key (API_USGS_FILES_PAT) is a second key, sent with requests
  for /stac-files/ and /stac/, so file downloads have their own hourly count.
- The pyarrow extra, which the bulk getters need. [test] includes it.
- On pandas 3, an OGC text column has the same type however the result was
  paged.

Split from DOI-USGS#476, which keeps the bulk setting that routes waterdata.get_daily()
and get_continuous() to the files, and ADR 0014.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- catalog: build each search through ogc.planning._try_build, so a filter
  over the 64 KB httpx can put in one URL component raises the ValueError
  with its remedy instead of httpx.InvalidURL.
- One _as_list, in catalog, for ratings, catalog.search and _retrieval.
- catalog.__all__ lists the names the bulk modules import.
- One masked renderer for api_key and files_api_key in show_configuration.
- ogc.errors._error_body reads the request URL and its key variables once.
- _change_clauses builds the set of changing locations once and floors the
  cutoffs as one DatetimeIndex.
- Without geopandas, the file rows' geometry is looked up once per location
  (pd.factorize), as with geopandas, instead of Series.map per row.
- qualifier: only the non-null lists are converted to Python objects
  (1.4M rows, 3% non-null: 27 ms to 12 ms).
- Wording: "the bulk getters" instead of "the files route".
- Tests: the ratings scoping test duplicated DOI-USGS#474's and is removed; the
  world-readable warning test covers both keys; the no-pyarrow fixture
  leaves conftest for a monkeypatch in its one test; _response uses
  inert_response.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With files_api_key, the catalog searches and file downloads count against
a second key, but md.header reported the lowest x-ratelimit-remaining of
every request, so it could show the files key's count as the API's. It now
reports the lowest among the requests sent the change query's key. With
one key, nothing changes.

The live comparison with the API getters compares types only for columns
with a value. The API getter types a column null in every row object, and
the bulk getter keeps the files' type; method_category at USGS-01435000 has
been null since 2026-10-01, so the test failed every run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…full record

Rename the second Water Data key from files_api_key / API_USGS_FILES_PAT to
stac_api_key / STAC_USGS_PAT, the variable R dataRetrieval reads, so one
export serves both packages.

Document the bulk getters by their main use first: omit time to get a
location's whole period of record. Add the example to the README, the
configuration guide, the getter docstrings and NEWS.

In get_urls, note that a location's current and historical continuous files
can both hold a record, and show how to keep the newest last_modified in
pandas and DuckDB. Scope the DuckDB example's secret to the Water Data host.

Print a one-time pointer to a STAC key when a catalog search or file
download is sent api_key because no STAC key is set. It is shown only for the
authorized host.

bulk._merge now orders file rows by last_modified, newest first, before
dropping duplicates, so the newer of two overlapping files wins whatever
order they were read in. Before, the first file read won.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1 Non-breaking: can merge for the next 1.x release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant