earth2studio-create-datasource
Создание и проверка обёрток источников данных Earth2Studio (DataSource, ForecastSource, DataFrameSource, ForecastFrameSource) из удалённых хранилищ. НЕ использовать для…
npx skills add https://github.com/nvidia/earth2studio --skill earth2studio-create-datasourceCreate and Validate Data Source
Purpose
End-to-end workflow for implementing a new Earth2Studio data source wrapper that connects a remote data store (S3, GCS, Azure, HTTP, HuggingFace) to Earth2Studio's async data fetching infrastructure, from analysis through implementation and validation, with optional contribution steps.
Scope
Default to a protocol-compatible wrapper in the user's separate Python project.
Unless intent is already explicit, ask:
"Are you planning to contribute this to NVIDIA Earth2Studio?"
Only an affirmative answer or explicit contribution intent enables contributor steps.
For local wrappers, use the project's layout, dependencies, style and test conventions;
no Earth2Studio repository changes or full repository test suite are required.
Use earth2studio-install for dependency setup, including NATTEN and FlashAttention.
Repository paths below are source references or contributor destinations, not local output paths.
If unavailable locally, consult matching-version sources on GitHub or the documentation site.
Preserve existing licenses in copied code, including reference skeleton SPDX headers.
These samples do not impose NVIDIA copyright on newly authored local code.
Prerequisites
- Python project environment with Earth2Studio installed via
earth2studio-install - Contributors only: a development checkout; configure fork/upstream remotes when submitting
- Access to the target remote data store (credentials if private)
- Python 3.11+ (
requires-python = ">=3.11,<3.15")
⚠️ Credential Safety: If the remote store requires authentication, credentials must be passed via environment variables only. Never hard-code secrets in source files. Before any git commit, verify no credentials are staged (check
git diff --cachedfor API keys, tokens, or passwords).
Workspace
Use the user's project root. For contributor Harbor tasks only, write to
/workspace/output/ preserving paths. Never read evals/targets/.
Instructions
Python Environment: Always use
uv run pythonor the local.venv. Never use the system Python directly.
Follow Steps 0-7 in order, adapting paths to the user's project. Step 7b applies to eligible sources in either scope. Steps 8-14 are contributor only.
[CONFIRM] gates: Step 1 (Source Type), Step 12 (Sanity-Check Plots), and Step 13 (Ready to Submit) require explicit user approval when those steps apply. All other
[CONFIRM]markers are advisory; present decisions inline and proceed without blocking.Deliverables first: Write the source file and relevant tests (Steps 6-7) before extended exploration, documentation, registration, CHANGELOG, or PR work. Local wrappers stop after Step 7b and lightweight verification. Contributors may skip integration/PR steps when the user asks for implementation only. Step 7b (temporal statistics) is included by default for regular-cadence gridded sources.
Before you finish: For local wrappers, run a small mocked fetch and relevant contract checks in the project's environment, including output dimensions, labels, units, grid/schema and invalid inputs. Report failures and skipped coverage. Contributors add and run the new source's test suite, relevant regression tests and these checks in the repo root:
uv run pytest test/data/test_<source>.py -x make format && make lint && make licenseBe concise: Avoid long architecture reports; summarize decisions in a few sentences and move on to file writes.
Hangs or User Feedback If agent becomes stuck or user provides a correction, review the relevant protocol and guidance. Report discrepancies; edit repository guidance only for contributions. Be concise.
One source type per invocation. Invoke again for companion types.
Source of truth: use current protocols and sources for the installed version. Read
earth2studio/data/base.py(protocols),earth2studio/lexicon/base.py(vocabulary/schema),earth2studio/utils/time.py(time tolerance),earth2studio/data/utils.py(fetch_data,plan_statistics,reduce_statistics),earth2studio/grids/__init__.py(grids,infer_grid,resolve_grid) andMIGRATION.md(1.0 checklist). Current reference implementations:gfs.py(GRIB, analysis + forecast, statistics),arco.py(Zarr, statistics),hrrr.py(projected grid),nnja.py(DataFrame).
Reference Files
Load these on demand during the relevant steps:
| File | Content | Load at |
|---|---|---|
references/reference-implementation.py | Obstore-backed source skeleton with FILL comments | Steps 6–10 |
references/reference-lexicon.py | Lexicon skeleton with FILL comments | Step 4 |
references/testing-guide.py | Local smoke checks and contributor test skeleton | Steps 7 and 11 |
references/temporal-statistics.py | Statistics skeleton, supported methods, mock test sample | Step 7b |
references/validation-guide.md | Plot templates, PR body template, Greptile handling | Steps 12–14 (optional, for templates) |
Workflow Overview
Step 0: Obtain reference → Step 1: Determine type → Step 2: Dependencies
→ Step 3: Set up deps → Step 4: Create lexicon → Step 5: Define vocab/schema
→ Step 6: Create skeleton → Step 7: Implement source
→ Step 7b: eligible temporal statistics → Local: lightweight verification, done
Contributor only: Step 8: Register
→ Step 9: Documentation → Step 10: CHANGELOG → Step 11: Tests
→ Step 12: Validate & plots (user confirms) → Step 13: PR + sanity comment
→ Step 14: Greptile review
Step 0 — Obtain Remote Data Store Reference
If $ARGUMENTS is provided, use it (URL → WebFetch; file path → read).
If empty, ask:
Please provide a URL, API documentation link, or description of the remote data store. This will be used to understand storage format, access pattern, variable inventory, temporal/spatial resolution.
Step 1 — Determine Source Type
| Protocol | Returns | Has lead_time? | Use |
|---|---|---|---|
| DataSource | xr.DataArray | No | Gridded analysis/reanalysis |
| ForecastSource | xr.DataArray | Yes | Gridded forecast |
| DataFrameSource | pd.DataFrame | No | Sparse/station obs |
| ForecastFrameSource | pd.DataFrame | Yes | Sparse forecast obs |
Key factors: gridded vs sparse → DataArray vs DataFrame; analysis vs forecast → Source vs ForecastSource.
Read the selected version's specs before implementing output behavior:
- E2S-01: Core Metadata for coordinates, attributes and DataFrame schemas.
- E2S-02: Grids for grid metadata and inference.
- E2S-03: Time Statistics for labels, windows, source responsibilities and reduction metadata.
- E2S-05: Fetch Data for dispatch, source backing/device and output requirements.
Use these as the contract, not a copied checklist in this skill. Consult
data/base.py for source signatures and device
conventions, and current sources such as hrrr.py for implementation examples.
Reuse existing grid, time-tolerance, statistics and source-composition helpers.
If a template differs from the selected version's spec, report the discrepancy.
[CONFIRM — Source Type]
Present recommended type with justification. Ask for confirmation unless the user has already explicitly confirmed that type.
Step 2 — Examine Remote Store & Propose Dependencies
Analyze: storage backend, file format, authentication, access pattern, temporal/spatial resolution, variable inventory.
Prefer Earth2Studio obstore helpers:
| Backend / format | Preferred | Avoid |
|---|---|---|
| S3/GCS/HTTP object files | obstore_store_from_url + obstore_fetch_to_cache | raw SDK clients |
| Cloud Zarr | obstore_zarr_store | hand-rolled fsspec/zarr stores |
| Azure/object auth | obstore.store.from_url via shared helpers | provider SDKs directly |
| HuggingFace | huggingface_hub (core dep) | custom scripts |
Only fall back to dedicated libraries when obstore/shared helpers cannot access the store.
Check the destination project's dependencies; only propose packages not already present.
Core deps include: obstore, zarr, netCDF4, h5py, pygrib,
huggingface-hub, pandas, pyarrow.
[CONFIRM — Dependencies & Access Pattern]
Present: backend, obstore helper/store URL, new packages (with license), auth method.
Step 3 - Set Up Dependencies
Load
references/reference-implementation.pyfrom Step 6 through Step 10. Loadreferences/reference-lexicon.pyduring Step 4.
If new packages needed:
- Present the package name(s), version constraints, and licenses to the user
- Confirm the user approves adding them before proceeding
- Use
earth2studio-installfor setup and the local project's dependency conventions - For contributions only, register approved dependencies in the repository's
dataextra and update its lockfile using the developer guide - Guard optional imports; use
OptionalDependencyFailurefor registered Earth2Studio extras, or the local project's error handling for local dependencies
Step 4 — Create Lexicon Class
Create a lexicon module in the user's project, or for contributions at
earth2studio/lexicon/<source_name>.py, with:
metaclass=LexiconTypeVOCAB: dict[str, str]mapping E2S names → remote keysget_item(cls, val)returningtuple[str, Callable]- Use
::separator for structured keys - Use
references/reference-lexicon.pyas the starting template
Map remote variables against E2STUDIO_VOCAB (in
earth2studio/lexicon/base.py).
[CONFIRM — Lexicon & Variable Mapping]
Present: class name, key format, full mapping table, modifiers, reference URL.
Step 5 - Define Vocabulary / Schema (if needed)
Local wrappers keep new mappings and schema fields in their own modules. Only
contributors update E2STUDIO_VOCAB / E2STUDIO_SCHEMA in Earth2Studio.
- New vocab: surface = descriptive abbrev; pressure =
{name}{level} - New schema fields: DataFrame sources only, check
E2STUDIO_SCHEMA
[CONFIRM — Vocabulary & Schema Updates]
Skip if no updates needed.
Step 6 — Create Skeleton Data Source File
Use references/reference-implementation.py as the starting template.
Write to the user's project; contributors use earth2studio/data/<source_name>.py.
Contributors use this canonical method ordering; local wrappers follow their project's organization while retaining the relevant source methods:
- Class constants
- SCHEMA
__init___async_init__call__fetch_create_tasksfetch_wrapperfetch_array_validate_time- Helpers
cachepropertyavailableclassmethod
Use async task dataclass pattern for parallel execution.
[CONFIRM — Skeleton]
Present: class name, file path, skeleton code, task dataclass.
Step 7 — Implement the Data Source & Tests
Validate alongside the source. Local wrappers need relevant smoke/contract checks in the project's test layout, with mocked I/O where possible. Contributors create
test/data/test_<filename>.pyand addtest_<source>_call_mockfor async sources.
Sync sources: Use prep_data_inputs/prep_forecast_inputs, direct __call__.
Add the optional device keyword only per the device convention above.
Async sources: See references/reference-implementation.py for required patterns:
_sync_async, gather_with_concurrency, async_retry, obstore_fetch_to_cache,
obstore_zarr_store for Zarr, try/finally cleanup in async fetch so both
direct async and synchronous calls remove temporary files on success or error.
Keep __call__ as the sync bridge; do not clean up twice. For overlapping calls
sharing a temporary directory, use _CleanupAfterLastCall inside fetch (see
OISST) so one call cannot delete another's files. Persistent caches are retained.
In tests, save cache_path = Path(ds.cache) before fetching and inspect that path
afterward: the cache getter may recreate the directory. Assert that temporary
paths do not exist, rather than calling iterdir() on a removed directory.
Exercise sync/async cleanup on success and error with mocked downloads.
Constructor params:
cache=True, verbose=True, async_timeout=600, async_workers=None,
retries=3 (plus optional device="cpu"). DataFrame sources add time_tolerance.
Step 7b — Temporal Statistics
Include native temporal statistics by default for regular-cadence gridded
sources in either scope. Keep implementation and checks in the selected project.
Tell the user which methods and cadence the source will support.
Skip if the user opts out or the source is unsuitable (e.g. climatology or
irregular DataFrame/station/satellite observations). fetch_data rejects
statistic labels for sources without native support.
Load references/temporal-statistics.py and follow it. In short:
- Document support in the source's class docstring using a
NoteheadedTemporal statistics:. List methods, label syntax, sampling cadence, window closure, and accumulation caveats. Store capability metadata in the source's lexicon asTIME_STATISTICS = ("mean", "sum", "min", "max")(or a subset), and expose that lexicon assource.lexicon. Omit this metadata for lexicons without native support (e.g. climatology). Do not add source-leveltime_statisticsortime_stepattributes. - Plan:
plain, stats, attrs = plan_statistics(variable, target_times, delta_t, supported=self.lexicon.TIME_STATISTICS, validate=self._validate_time, ...).plainis[(slot, name)]fetched with the source's ordinary path;statsis a list ofStatisticPlandataclasses withslot,base,modifier, andsamplesfields.sampleshas shape(target, sample).target_timesare valid times, or the lead times of one initialization for forecasts. - Validate:
plan_statisticspasses every unique sample coordinate tovalidatebefore anything is downloaded. Irregular sources build their own sample lists fromtime_statistic_metadata. - Reduce:
await reduce_statistics(out, stats, fetch)whereoutis the(target, variable, ...)output view (one per initialization for forecasts) andfetch(coord, base)is a source coroutine returning one lexicon-converted field. Each target's samples are stacked in a transient array, reduced through the registered statistic (reduce_samples), written toout, and released. New registered statistics work without source changes (add toTIME_STATISTICS). - Finish: propagate fetch errors and set
xr_array.attrs.update(attrs). - Tell the user: the helper's
verbose=Truereports what is averaged/accumulated/min'd/max'd and the window. Warn about fields that are already accumulations (e.g. resetting precipitation buckets).
Label grammar: var:method:window (trailing, (-w, 0]) or
var:method:start:end (e.g. tp:sum:+0h:+6h); windows are left-open,
right-closed. Regular coordinate helpers require cadence-aligned windows; reduction
itself imposes no cadence and uses sample-weighted means. Parsing is in
earth2studio/utils/time_statistics.py; reuse it, do not re-parse labels.
Testing: locally, exercise supported reductions, metadata and invalid windows
with a small mocked case. For contributions, use exactly one mock test
(extend test_<source>_call_mock if present,
otherwise add test_<source>_time_statistics_mock),
covering mean/sum/min/max, the attrs, the planned samples read, and an invalid
window (forecast sources also lead-time overlap, separate initializations, and
lead < 0). Mock I/O, not the planner or reducer. The sample is in
references/temporal-statistics.py; contributor fixtures mock_statistic_zarr and
mock_statistic_grib are in test/data/conftest.py. Local projects may adapt the
sample with their own fixtures and imports.
Step 8 - Register the Source (contributor only)
earth2studio/data/__init__.py— alphabetical importearth2studio/lexicon/__init__.py— alphabetical import- Verify
pyproject.tomldeps
Step 9 - Update Documentation (contributor only)
- Add the class alphabetically to the appropriate autosummary block in
docs/modules/datasources_analysis.md,datasources_forecast.md, ordatasources_dataframe.md(MkDocs; there is no Sphinx.rstregistration) - Class docstring: Parameters, Warning (download size), Note (reference URLs), Badges (last)
- Keep the existing
region,dataclass, andproductbadges accurate. Addprovider:<name>when the service provider is known, and adddataset:<family>only when the source belongs to a named dataset family; do not infer a family from the provider. Usedataset:gfsfor GEFS sources. - Reuse lowercase badge keys already defined in
mkdocs.yml. If a new provider or dataset family is required, add its badge definition there and usehide_in: [autosummary, filter]; the catalog reads these badges even though data-source API tables do not display or filter on them. - Example:
region:global dataclass:reanalysis dataset:era5 product:atmos provider:google - All public methods: NumPy-style docstrings
Step 10 - Update CHANGELOG.md (contributor only)
Add entry under the current unreleased version. See
references/reference-implementation.py REGISTRATION CHECKLIST for the format.
One line per source. Do NOT add separate lexicon entries.
Step 11 - Verify Style & Expand Tests (contributor only)
Run make format && make lint && make license. Load references/testing-guide.py
for test skeletons. Required tests: test_<source>_fetch (slow), _cache (slow),
_call_mock, _exceptions, _available; plus a single
_time_statistics_mock only if Step 7b was done. Target 90%+ coverage with --slow.
[CONFIRM — Tests]
Present test file, functions, coverage.
Step 12 - Validate Variables & Sanity-Check (contributor only)
- Validate all lexicon vars against real data (run script, do NOT commit)
- Remove variables with < 10% valid data
- Create sanity-check plot (gridded or sparse template)
- Tell user the plot path and ask for visual confirmation
[CONFIRM — Sanity-Check Plots]
User MUST visually inspect plots. Do not proceed without confirmation.
Step 13 - Branch, Commit & Open PR (contributor only, when requested)
⚠️ WARNING: This step performs irreversible git operations (push, PR creation). Do NOT proceed without explicit user confirmation. Present all planned git commands to the user and wait for approval.
- Create branch
feat/data-source-<name> - Commit (do NOT add sanity-check script/images)
- Present full command list to user for review
- Push to fork (only after user approves)
gh pr create --repo NVIDIA/earth2studio(only after user approves)- Immediately post sanity-check validation as PR comment with:
- Variable coverage table (name, count, range, unit)
- Data validation summary (regions, storms/stations, time range)
- Key findings (physically reasonable values, conversions verified)
- Full validation script in
<details>block - Image placeholder:
<!-- Drag and drop sanity-check image here -->
[CONFIRM — Ready to Submit] (MANDATORY)
This gate is MANDATORY and blocks all git push/PR operations. Present the following to the user and wait for explicit approval:
- List of all files to be committed
- Full git commands that will be executed (push, PR create)
- Target repository and branch
- Warning: "These operations are irreversible and will be visible publicly"
Do NOT push or create PRs until the user explicitly confirms.
Step 14 - Automated Code Review (contributor only)
- Poll for Greptile review (5 min timeout)
- Categorize feedback (bug/style/perf/docs/suggestion/false-positive)
- Present triage table to user
- Wait for user to approve which comments to address and which to dismiss
- Implement accepted fixes
- Respond to PR comments (only with user-approved actions)
- Push (with user confirmation)
[CONFIRM — Review Triage]
User approves which comments to address and which to dismiss. Never dismiss code review feedback autonomously.
Examples
User: Add a data source for the NOAA GFS analysis on S3 in my own project, no contribution.
Agent: [uses Steps 0-7b and local smoke/contract validation]
User: I want to contribute this data source to NVIDIA Earth2Studio.
Agent: [uses contributor paths and checks; submission requires an explicit request]
Limitations
- One source type per invocation
- Requires network access for validation (Step 12)
- Contributors add SPDX headers to newly authored repository code; preserve copied licenses
Reminders
DO: use the project environment and conventions; contributors use loguru.logger
and alphabetical order in __init__.py/docs autosummary/CHANGELOG. Use
optional device per the protocol guidance, obstore helpers,
gather_with_concurrency, async_retry,
reference URLs in docstrings, try/finally cleanup.
Temporal statistics: include for regular-cadence gridded sources; reuse plan_statistics / reduce_statistics from
earth2studio/data/utils.py; one transient window stack per target, never the whole request.
AVOID: hand-rolled fsspec stores, asyncio.to_thread, bare tqdm.gather,
xarray for loading, full file downloads.
NEVER: loop.set_default_executor(), commit secrets, commit sanity-check scripts/images.
Contributor Checklist
Only for confirmed contributions, follow CONTRIBUTING.md and the developer guide:
- Register approved dependencies, exports, vocabulary/schema, catalog and changelog updates.
- Apply repository style and SPDX requirements; preserve copied licenses.
- Add and run source tests and relevant regressions, plus
make format,make lint,make license; report unavailable dependencies and skipped coverage. - Use Steps 12-14 and the validation guide for contribution review. Commit, push and open a PR only when explicitly requested.