:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement cimis import source (#66764)
Tom Owersbb9c6e47da61
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 537656ceeea1..4f1b34531c59 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -82,6 +82,7 @@ the row lists both.| confluence | HTTP | requests | ✅ || chartmogul | HTTP | requests | ✅ || circleci | HTTP | requests | ✅ |+| cimis | HTTP | requests | ✅ || cloudflare | HTTP | requests | ✅ || clari | HTTP | requests | ✅ || clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -340,7 +341,6 @@ doesn't conflict with concurrent PRs.- chift- chorus- churnkey-- cimis- cin7- cisco_meraki- clarifaidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/canonical_descriptions.pynew file mode 100644index 000000000000..01e4c0252ce5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/canonical_descriptions.py@@ -0,0 +1,81 @@+"""Canonical, documentation-sourced descriptions for CIMIS endpoints and columns.++Sourced from the official CIMIS Web API reference (https://et.water.ca.gov/Rest/Index). Keyed by the+endpoint names in `settings.py` `CIMIS_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced+CIMIS table. Columns absent here fall back to LLM enrichment. The weather-data tables flatten each nested+measurement object into `<Item>_Value`, `<Item>_Qc`, and `<Item>_Unit` columns, so only the shared+identity columns are described here; the per-measurement columns fall back to the LLM.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DATA_DOCS_URL = "https://et.water.ca.gov/Rest/Index"++_DATA_IDENTITY_COLUMNS = {+ "Date": "Calendar date of the observation (yyyy-mm-dd).",+ "Julian": "Day of the year (1-366) for the observation date.",+ "Station": "CIMIS station number the observation came from.",+ "Standard": "Unit system the values are reported in (english or metric).",+ "ZipCodes": "Zip codes served by the station for this record.",+ "Scope": "Granularity of the record (daily or hourly).",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "stations": {+ "description": "Metadata for every CIMIS weather station, including location, elevation, and active status.",+ "docs_url": "https://et.water.ca.gov/Rest/Index",+ "columns": {+ "StationNbr": "Unique CIMIS station number.",+ "Name": "Station name.",+ "City": "City the station is located in.",+ "RegionalOffice": "CIMIS regional office responsible for the station.",+ "County": "County the station is located in.",+ "ConnectDate": "Date the station was connected to the network.",+ "DisconnectDate": "Date the station was disconnected (a far-future date if still active).",+ "IsActive": "Whether the station is currently active.",+ "IsEtoStation": "Whether the station reports reference evapotranspiration (ETo).",+ "Elevation": "Station elevation.",+ "GroundCover": "Ground cover at the station (e.g. grass).",+ "HmsLatitude": "Station latitude in degrees-minutes-seconds and decimal form.",+ "HmsLongitude": "Station longitude in degrees-minutes-seconds and decimal form.",+ "ZipCodes": "Zip codes served by the station.",+ "SitingDesc": "Description of the station siting.",+ },+ },+ "station_zipcodes": {+ "description": "Mapping of zip codes to the CIMIS Weather Station Network station that serves them.",+ "docs_url": "https://et.water.ca.gov/Rest/Index",+ "columns": {+ "StationNbr": "CIMIS station number serving the zip code.",+ "ZipCode": "Zip code served by the station.",+ "ConnectDate": "Date the zip code was associated with the station.",+ "DisconnectDate": "Date the association ended (a far-future date if still active).",+ "IsActive": "Whether the association is currently active.",+ },+ },+ "spatial_zipcodes": {+ "description": "Zip codes supported by the Spatial CIMIS System (2km gridded interpolated data).",+ "docs_url": "https://et.water.ca.gov/Rest/Index",+ "columns": {+ "ZipCode": "Supported zip code.",+ "ConnectDate": "Date the zip code became available in the spatial system.",+ "DisconnectDate": "Date the zip code support ended (a far-future date if still active).",+ "IsActive": "Whether the zip code is currently supported.",+ },+ },+ "daily_data": {+ "description": "Daily weather and reference evapotranspiration (ETo) observations per station.",+ "docs_url": _DATA_DOCS_URL,+ "columns": _DATA_IDENTITY_COLUMNS,+ },+ "hourly_data": {+ "description": "Hourly weather and reference evapotranspiration (ETo) observations per station.",+ "docs_url": _DATA_DOCS_URL,+ "columns": {+ **_DATA_IDENTITY_COLUMNS,+ "Hour": "Hour of the observation in HHMM form (e.g. 100 = 01:00).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/cimis.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/cimis.pynew file mode 100644index 000000000000..7dca15b92c84--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/cimis.py@@ -0,0 +1,308 @@+from collections.abc import Iterator, Sequence+from datetime import date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import urlencode+from zoneinfo import ZoneInfo++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.cimis.settings import (+ CIMIS_BASE_URL,+ CIMIS_DATA_EPOCH,+ CIMIS_ENDPOINTS,+ CIMIS_RECORD_CAP,+ DEFAULT_DAILY_DATA_ITEMS,+ DEFAULT_HOURLY_DATA_ITEMS,+ CimisEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session++REQUEST_TIMEOUT = 60+# CIMIS sits behind a WAF that rejects requests without a browser-like User-Agent.+_USER_AGENT = "PostHog-DataWarehouse/1.0 (+https://posthog.com)"+# CIMIS rejects future dates relative to California local time, so the request upper bound is computed+# in the station network's timezone rather than UTC.+_CALIFORNIA_TZ = ZoneInfo("America/Los_Angeles")+++def _california_today() -> date:+ return datetime.now(_CALIFORNIA_TZ).date()+++class CimisRetryableError(Exception):+ pass+++class CimisHTTPError(Exception):+ """Sanitized HTTP error for non-2xx CIMIS responses.++ requests' own ``raise_for_status()`` embeds the full request URL — which carries the appKey in+ its query string — in the exception message, so it must not be used here. This error reports only+ the status code, keeping the credential out of logs, error tracking, and the non-retryable matcher.+ """++ def __init__(self, status_code: int) -> None:+ self.status_code = status_code+ super().__init__(f"CIMIS API error: status={status_code}")+++def _headers() -> dict[str, str]:+ return {"Accept": "application/json", "User-Agent": _USER_AGENT}+++def _records_per_day(scope: Optional[str]) -> int:+ return 24 if scope == "hourly" else 1+++def _default_data_items(scope: Optional[str]) -> list[str]:+ return DEFAULT_HOURLY_DATA_ITEMS if scope == "hourly" else DEFAULT_DAILY_DATA_ITEMS+++def parse_targets(targets: str | None) -> list[str]:+ if not targets:+ return []+ return [t.strip() for t in targets.split(",") if t.strip()]+++def _chunk(items: Sequence[str], size: int) -> Iterator[list[str]]:+ for i in range(0, len(items), max(1, size)):+ yield list(items[i : i + size])+++def _to_date(value: Any) -> date | None:+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ try:+ return datetime.fromisoformat(str(value)[:10]).date()+ except ValueError:+ return None+++def _date_windows(start: date, end: date, window_days: int) -> Iterator[tuple[date, date]]:+ """Yield inclusive [win_start, win_end] date windows from start to end, oldest first."""+ cursor = start+ step = max(1, window_days)+ while cursor <= end:+ win_end = min(cursor + timedelta(days=step - 1), end)+ yield cursor, win_end+ cursor = win_end + timedelta(days=1)+++def _flatten_record(record: dict[str, Any]) -> dict[str, Any]:+ """Flatten CIMIS measurement objects ({Value, Qc, Unit}) into scalar columns.++ Each /api/data record carries scalar identity fields (Date, Hour, Station, ...) plus one nested+ object per requested measurement, e.g. ``"DayAirTmpAvg": {"Value": "12.3", "Qc": " ", "Unit": "(F)"}``.+ Nested measurement objects become ``DayAirTmpAvg_Value`` / ``_Qc`` / ``_Unit`` columns so the table+ stays flat; everything else is passed through untouched.+ """+ flat: dict[str, Any] = {}+ for key, value in record.items():+ if isinstance(value, dict) and ("Value" in value or "Qc" in value or "Unit" in value):+ for sub_key, sub_value in value.items():+ flat[f"{key}_{sub_key}"] = sub_value+ else:+ flat[key] = value+ return flat+++@retry(+ retry=retry_if_exception_type((CimisRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ response = session.get(url, timeout=REQUEST_TIMEOUT)++ if response.status_code == 429 or response.status_code >= 500:+ raise CimisRetryableError(f"CIMIS API error (retryable): status={response.status_code}")++ if not response.ok:+ logger.error(f"CIMIS API error: status={response.status_code}, body={response.text[:500]}")+ raise CimisHTTPError(response.status_code)++ return response.json()+++def _build_metadata_url(config: CimisEndpointConfig, app_key: str) -> str:+ # The metadata endpoints (station / stationzipcode / spatialzipcode) ignore appKey today, but we+ # send it so behavior stays correct if CIMIS starts enforcing it on these paths.+ return f"{CIMIS_BASE_URL}{config.path}?{urlencode({'appKey': app_key})}"+++def _build_data_url(+ app_key: str,+ targets: list[str],+ unit_of_measure: str,+ data_items: list[str],+ start: date,+ end: date,+) -> str:+ params = {+ "appKey": app_key,+ "targets": ",".join(targets),+ "startDate": start.isoformat(),+ "endDate": end.isoformat(),+ "unitOfMeasure": unit_of_measure,+ "dataItems": ",".join(data_items),+ }+ return f"{CIMIS_BASE_URL}/data?{urlencode(params)}"+++def _iter_data_records(data: dict[str, Any]) -> Iterator[dict[str, Any]]:+ providers = data.get("Data", {}).get("Providers", [])+ for provider in providers:+ for record in provider.get("Records", []):+ yield _flatten_record(record)+++def _get_metadata_rows(+ config: CimisEndpointConfig, app_key: str, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session(headers=_headers(), redact_values=(app_key,))+ url = _build_metadata_url(config, app_key)+ data = _fetch(session, url, logger)+ rows = data.get(config.response_key, [])+ if rows:+ yield rows+++def _get_data_rows(+ config: CimisEndpointConfig,+ app_key: str,+ targets: list[str],+ unit_of_measure: str,+ data_items: list[str],+ start: date,+ end: date,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ if not targets:+ raise ValueError(+ "CIMIS weather data tables require at least one target station. Set the 'Targets' field "+ "on the source to a comma-separated list of CIMIS station numbers."+ )++ session = make_tracked_session(headers=_headers(), redact_values=(app_key,))+ rpd = _records_per_day(config.scope)++ # Keep the date window as the outer loop so rows are emitted in ascending Date order even when the+ # target set is large enough to require multiple requests per window (sort_mode="asc" relies on it).+ if len(targets) * rpd <= CIMIS_RECORD_CAP:+ window_days = max(1, CIMIS_RECORD_CAP // (len(targets) * rpd))+ target_batches = [targets]+ else:+ window_days = 1+ target_batches = list(_chunk(targets, max(1, CIMIS_RECORD_CAP // rpd)))++ for win_start, win_end in _date_windows(start, end, window_days):+ for batch in target_batches:+ url = _build_data_url(app_key, batch, unit_of_measure, data_items, win_start, win_end)+ data = _fetch(session, url, logger)+ rows = list(_iter_data_records(data))+ if rows:+ yield rows+++def get_rows(+ endpoint: str,+ app_key: str,+ targets: list[str],+ unit_of_measure: str,+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = CIMIS_ENDPOINTS[endpoint]++ if not config.is_data_endpoint:+ yield from _get_metadata_rows(config, app_key, logger)+ return++ # CIMIS has no future data and rejects future dates; the upper bound is always today in California.+ end = _california_today()++ start = date.fromisoformat(CIMIS_DATA_EPOCH)+ if should_use_incremental_field:+ last_value = _to_date(db_incremental_field_last_value)+ if last_value is not None:+ # Re-fetch from the last seen day (inclusive); merge dedupes on the primary key.+ start = last_value++ if start > end:+ return++ yield from _get_data_rows(+ config, app_key, targets, unit_of_measure, _default_data_items(config.scope), start, end, logger+ )+++def validate_credentials(app_key: str, targets: list[str], logger: FilteringBoundLogger) -> tuple[bool, str | None]:+ """Probe /api/data with a tiny recent window to confirm the appKey is genuine.++ The metadata endpoints don't enforce the appKey, so the only key-gated probe is /api/data. We use+ a known-good public station (2 = FivePoints) when the user hasn't supplied targets yet so source+ creation isn't gated on the targets field.++ Note: this endpoint could not be exercised end-to-end during development (the live API is fronted+ by a WAF that rejected automated probes from the build environment), so the status mapping below+ follows the documented CIMIS error contract rather than observed responses.+ """+ probe_target = targets[0] if targets else "2"+ end = _california_today()+ start = end - timedelta(days=2)+ url = _build_data_url(app_key, [probe_target], "E", ["day-air-tmp-avg"], start, end)++ try:+ session = make_tracked_session(headers=_headers(), redact_values=(app_key,))+ response = session.get(url, timeout=REQUEST_TIMEOUT)+ except Exception as exc:+ # Log only the exception type — requests exceptions embed the request URL, which carries the appKey.+ logger.warning(f"CIMIS credential validation failed to reach the API: {type(exc).__name__}")+ return False, "Could not reach the CIMIS API. Please try again."++ if response.status_code == 200:+ return True, None++ if response.status_code in (401, 403):+ return False, "Your CIMIS appKey is invalid or has not been activated. Check the key and try again."++ return False, f"CIMIS API returned status {response.status_code}."+++def cimis_source(+ endpoint: str,+ app_key: str,+ targets: list[str],+ unit_of_measure: str,+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = CIMIS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ endpoint=endpoint,+ app_key=app_key,+ targets=targets,+ unit_of_measure=unit_of_measure,+ logger=logger,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/settings.pynew file mode 100644index 000000000000..029f086d3813--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/settings.py@@ -0,0 +1,125 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# CIMIS (California Irrigation Management Information System) Web API base URL.+# https://et.water.ca.gov/Rest/Index+CIMIS_BASE_URL = "https://et.water.ca.gov/api"++# CIMIS rejects a single /api/data request that would return more than ~1750 records (ERR2112).+# We chunk by date window and target set to stay comfortably under that ceiling.+CIMIS_RECORD_CAP = 1700++# Earliest date CIMIS has data for. Used as the backfill floor when the user doesn't pin a start date.+CIMIS_DATA_EPOCH = "1982-06-07"++# Default measurement items requested per scope when the user doesn't override them. These are the+# core, broadly-available CIMIS data item codes; the response flattener handles whatever the API+# actually returns, so this list only governs which measurements we ask for.+DEFAULT_DAILY_DATA_ITEMS = [+ "day-asce-eto",+ "day-eto",+ "day-precip",+ "day-sol-rad-avg",+ "day-vap-pres-avg",+ "day-air-tmp-max",+ "day-air-tmp-min",+ "day-air-tmp-avg",+ "day-rel-hum-max",+ "day-rel-hum-min",+ "day-rel-hum-avg",+ "day-dew-pnt",+ "day-wind-spd-avg",+ "day-wind-run",+ "day-soil-tmp-avg",+]+DEFAULT_HOURLY_DATA_ITEMS = [+ "hly-air-tmp",+ "hly-dew-pnt",+ "hly-eto",+ "hly-asce-eto",+ "hly-precip",+ "hly-rel-hum",+ "hly-res-wind",+ "hly-soil-tmp",+ "hly-sol-rad",+ "hly-vap-pres",+ "hly-wind-dir",+ "hly-wind-spd",+]+++@dataclass+class CimisEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # JSON key wrapping the list of rows in the response body (e.g. "Stations", "ZipCodes").+ response_key: str = ""+ # /api/data endpoints are date-windowed pulls keyed by station targets; the metadata endpoints+ # are single full-refresh requests.+ is_data_endpoint: bool = False+ # "daily" or "hourly" — only meaningful for data endpoints.+ scope: Optional[str] = None+ partition_key: Optional[str] = None+ should_sync_default: bool = True+++_DATE_INCREMENTAL_FIELD: IncrementalField = {+ "label": "Date",+ "type": IncrementalFieldType.Date,+ "field": "Date",+ "field_type": IncrementalFieldType.Date,+}+++CIMIS_ENDPOINTS: dict[str, CimisEndpointConfig] = {+ "stations": CimisEndpointConfig(+ name="stations",+ path="/station",+ response_key="Stations",+ primary_keys=["StationNbr"],+ ),+ "station_zipcodes": CimisEndpointConfig(+ name="station_zipcodes",+ path="/stationzipcode",+ response_key="ZipCodes",+ # A zip code maps to one station, but the same station owns many zip codes, so the row is+ # only unique on the pair.+ primary_keys=["StationNbr", "ZipCode"],+ ),+ "spatial_zipcodes": CimisEndpointConfig(+ name="spatial_zipcodes",+ path="/spatialzipcode",+ response_key="ZipCodes",+ primary_keys=["ZipCode"],+ ),+ "daily_data": CimisEndpointConfig(+ name="daily_data",+ path="/data",+ is_data_endpoint=True,+ scope="daily",+ # One record per station per day. Date is a stable, monotonic field.+ primary_keys=["Station", "Date"],+ partition_key="Date",+ incremental_fields=[_DATE_INCREMENTAL_FIELD],+ ),+ "hourly_data": CimisEndpointConfig(+ name="hourly_data",+ path="/data",+ is_data_endpoint=True,+ scope="hourly",+ # One record per station per hour. Hour disambiguates within a day.+ primary_keys=["Station", "Date", "Hour"],+ partition_key="Date",+ incremental_fields=[_DATE_INCREMENTAL_FIELD],+ ),+}++ENDPOINTS = tuple(CIMIS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CIMIS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/source.pyindex 72af465b4476..dac09df3f6a8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/source.py@@ -1,19 +1,48 @@-from typing import cast+from typing import Optional, cast++import structlogfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cimis.cimis import (+ cimis_source,+ parse_targets,+ validate_credentials as validate_cimis_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cimis.settings import (+ CIMIS_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CimisSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass CimisSource(SimpleSource[CimisSourceConfig]):+ # get_schemas iterates a static endpoint catalog with no I/O, so the table list is safe to surface+ # in public docs without credentials.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CIMIS@@ -24,7 +53,103 @@ class CimisSource(SimpleSource[CimisSourceConfig]):name=SchemaExternalDataSourceType.CIMIS,category=DataWarehouseSourceCategory.ANALYTICS,label="CIMIS",- iconPath="/static/services/cimis.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Pull California weather and reference evapotranspiration (ETo) data from the [California Irrigation Management Information System (CIMIS)](https://cimis.water.ca.gov/) into the PostHog Data warehouse.++CIMIS is a free service. Register for a free account and create a **web-services appKey** in your [CIMIS account](https://et.water.ca.gov/Account/Login), then paste it below.++To sync the **daily** and **hourly** weather tables, set **Targets** to a comma-separated list of CIMIS station numbers (e.g. `2,8,127`). You can look up station numbers in the `stations` table or on the [CIMIS station map](https://cimis.water.ca.gov/Stations.aspx). The station and zip-code metadata tables sync without targets.""",+ iconPath="/static/services/cimis.png",+ docsUrl="https://posthog.com/docs/cdp/sources/cimis",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="app_key",+ label="App key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="your CIMIS web-services appKey",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="targets",+ label="Targets (station numbers)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2,8,127",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="unit_of_measure",+ label="Unit of measure",+ required=False,+ defaultValue="E",+ options=[+ SourceFieldSelectConfigOption(label="English (°F, inches)", value="E"),+ SourceFieldSelectConfigOption(label="Metric (°C, mm)", value="M"),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cimis.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Matches the sanitized CimisHTTPError message (status code only) so the appKey embedded in the+ # request URL never reaches the matcher, logs, or error tracking.+ return {+ "CIMIS API error: status=401": "Your CIMIS appKey is invalid or has expired. Create a new appKey in your CIMIS account, then reconnect.",+ "CIMIS API error: status=403": "Your CIMIS appKey is invalid or has not been activated. Check the key in your CIMIS account, then reconnect.",+ }++ def get_schemas(+ self,+ config: CimisSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = CIMIS_ENDPOINTS[endpoint]+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: CimisSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ logger = structlog.get_logger(__name__)+ return validate_cimis_credentials(config.app_key, parse_targets(config.targets), logger)++ def source_for_pipeline(self, config: CimisSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return cimis_source(+ endpoint=inputs.schema_name,+ app_key=config.app_key,+ targets=parse_targets(config.targets),+ unit_of_measure=config.unit_of_measure or "E",+ logger=inputs.logger,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis.pynew file mode 100644index 000000000000..1537860b610f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis.py@@ -0,0 +1,273 @@+from datetime import date+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.cimis import cimis+from products.warehouse_sources.backend.temporal.data_imports.sources.cimis.cimis import (+ _date_windows,+ _flatten_record,+ _iter_data_records,+ cimis_source,+ get_rows,+ parse_targets,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cimis.settings import (+ CIMIS_ENDPOINTS,+ CIMIS_RECORD_CAP,+)+++class TestParseTargets:+ @parameterized.expand(+ [+ ("none", None, []),+ ("empty", "", []),+ ("single", "2", ["2"]),+ ("multiple", "2,8,127", ["2", "8", "127"]),+ ("whitespace_and_blanks", " 2 , ,8 ,", ["2", "8"]),+ ]+ )+ def test_parse_targets(self, _name: str, raw: str | None, expected: list[str]) -> None:+ assert parse_targets(raw) == expected+++class TestFlattenRecord:+ def test_flattens_measurement_objects_into_scalar_columns(self) -> None:+ record = {+ "Date": "2023-01-01",+ "Station": "2",+ "Scope": "daily",+ "DayAirTmpAvg": {"Value": "50.1", "Qc": " ", "Unit": "(F)"},+ }+ flat = _flatten_record(record)+ assert flat["Date"] == "2023-01-01"+ assert flat["Station"] == "2"+ assert flat["DayAirTmpAvg_Value"] == "50.1"+ assert flat["DayAirTmpAvg_Qc"] == " "+ assert flat["DayAirTmpAvg_Unit"] == "(F)"+ # The nested object itself should not survive as a column.+ assert "DayAirTmpAvg" not in flat++ def test_leaves_non_measurement_values_untouched(self) -> None:+ # ZipCodes is a list, not a {Value, Qc, Unit} measurement object, so it passes through.+ record = {"Station": "2", "ZipCodes": ["93624"]}+ flat = _flatten_record(record)+ assert flat["ZipCodes"] == ["93624"]+++class TestDateWindows:+ def test_single_day_windows(self) -> None:+ windows = list(_date_windows(date(2023, 1, 1), date(2023, 1, 3), 1))+ assert windows == [+ (date(2023, 1, 1), date(2023, 1, 1)),+ (date(2023, 1, 2), date(2023, 1, 2)),+ (date(2023, 1, 3), date(2023, 1, 3)),+ ]++ def test_multi_day_windows_clamp_to_end(self) -> None:+ windows = list(_date_windows(date(2023, 1, 1), date(2023, 1, 5), 2))+ assert windows == [+ (date(2023, 1, 1), date(2023, 1, 2)),+ (date(2023, 1, 3), date(2023, 1, 4)),+ (date(2023, 1, 5), date(2023, 1, 5)),+ ]++ def test_single_window_when_range_smaller_than_window(self) -> None:+ windows = list(_date_windows(date(2023, 1, 1), date(2023, 1, 2), 30))+ assert windows == [(date(2023, 1, 1), date(2023, 1, 2))]+++class TestIterDataRecords:+ def test_iterates_records_across_providers_and_flattens(self) -> None:+ payload = {+ "Data": {+ "Providers": [+ {"Name": "cimis", "Records": [{"Date": "2023-01-01", "DayEto": {"Value": "0.05"}}]},+ {"Name": "scs", "Records": [{"Date": "2023-01-02", "DayEto": {"Value": "0.06"}}]},+ ]+ }+ }+ rows = list(_iter_data_records(payload))+ assert [r["Date"] for r in rows] == ["2023-01-01", "2023-01-02"]+ assert rows[0]["DayEto_Value"] == "0.05"++ def test_empty_payload_yields_nothing(self) -> None:+ assert list(_iter_data_records({})) == []+++def _data_payload(station: str, day: str) -> dict[str, Any]:+ return {+ "Data": {+ "Providers": [+ {"Name": "cimis", "Records": [{"Date": day, "Station": station, "DayEto": {"Value": "0.05"}}]}+ ]+ }+ }+++class TestGetRowsMetadata:+ def test_metadata_endpoint_yields_response_key_rows(self, monkeypatch: Any) -> None:+ captured: list[str] = []++ def fake_fetch(_session: Any, url: str, _logger: Any) -> dict[str, Any]:+ captured.append(url)+ return {"Stations": [{"StationNbr": "2"}, {"StationNbr": "8"}]}++ monkeypatch.setattr(cimis, "_fetch", fake_fetch)+ batches = list(get_rows(endpoint="stations", app_key="k", targets=[], unit_of_measure="E", logger=mock.Mock()))++ assert batches == [[{"StationNbr": "2"}, {"StationNbr": "8"}]]+ assert len(captured) == 1+ assert "/station" in captured[0]+++class TestGetRowsData:+ def test_data_endpoint_requires_targets(self) -> None:+ with pytest.raises(ValueError):+ list(get_rows(endpoint="daily_data", app_key="k", targets=[], unit_of_measure="E", logger=mock.Mock()))++ @freeze_time("2023-01-03 12:00:00")+ def test_daily_full_refresh_windows_from_epoch(self, monkeypatch: Any) -> None:+ urls: list[str] = []++ def fake_fetch(_session: Any, url: str, _logger: Any) -> dict[str, Any]:+ urls.append(url)+ return _data_payload("2", "2023-01-01")++ monkeypatch.setattr(cimis, "_fetch", fake_fetch)+ # Few targets and a large per-request cap means a single window covers the whole range.+ batches = list(+ get_rows(endpoint="daily_data", app_key="k", targets=["2"], unit_of_measure="E", logger=mock.Mock())+ )+ assert len(batches) >= 1+ assert all("startDate=" in u and "endDate=" in u for u in urls)+ # No request may reach into the future.+ assert all("endDate=2023-01-03" in u for u in urls[-1:])++ @freeze_time("2023-01-10 12:00:00")+ def test_daily_incremental_starts_from_last_value(self, monkeypatch: Any) -> None:+ urls: list[str] = []++ def fake_fetch(_session: Any, url: str, _logger: Any) -> dict[str, Any]:+ urls.append(url)+ return _data_payload("2", "2023-01-08")++ monkeypatch.setattr(cimis, "_fetch", fake_fetch)+ list(+ get_rows(+ endpoint="daily_data",+ app_key="k",+ targets=["2"],+ unit_of_measure="E",+ logger=mock.Mock(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2023, 1, 8),+ )+ )+ # The first window must begin at the saved watermark, not the epoch.+ assert "startDate=2023-01-08" in urls[0]++ @freeze_time("2023-01-02 12:00:00")+ def test_no_requests_when_watermark_in_future(self, monkeypatch: Any) -> None:+ urls: list[str] = []++ def fake_fetch(_session: Any, url: str, _logger: Any) -> dict[str, Any]:+ urls.append(url)+ return _data_payload("2", "2023-01-01")++ monkeypatch.setattr(cimis, "_fetch", fake_fetch)+ batches = list(+ get_rows(+ endpoint="daily_data",+ app_key="k",+ targets=["2"],+ unit_of_measure="E",+ logger=mock.Mock(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2030, 1, 1),+ )+ )+ assert batches == []+ assert urls == []++ @freeze_time("2020-01-01 12:00:00")+ def test_hourly_with_many_targets_keeps_each_request_under_cap(self, monkeypatch: Any) -> None:+ # 100 hourly targets over a single day would be 2400 records — over the cap — so the source+ # must split the target set and keep the date window at a single day.+ seen_requests: list[tuple[str, str, int]] = []++ def fake_fetch(_session: Any, url: str, _logger: Any) -> dict[str, Any]:+ # Parse start/end + target count out of the URL to assert the per-request volume.+ params = dict(p.split("=", 1) for p in url.split("?", 1)[1].split("&"))+ n_targets = len(params["targets"].split("%2C")) if "%2C" in params["targets"] else 1+ seen_requests.append((params["startDate"], params["endDate"], n_targets))+ return _data_payload("1", "2019-12-31")++ monkeypatch.setattr(cimis, "_fetch", fake_fetch)+ targets = [str(i) for i in range(1, 101)]+ # Single-day range so we only probe the target-splitting dimension.+ with mock.patch.object(cimis, "CIMIS_DATA_EPOCH", "2019-12-31"):+ list(+ get_rows(endpoint="hourly_data", app_key="k", targets=targets, unit_of_measure="E", logger=mock.Mock())+ )++ assert seen_requests, "expected at least one request"+ for _start, _end, n_targets in seen_requests:+ # 24 records/day/target * n_targets * window_days(=1) must stay under the cap.+ assert n_targets * 24 <= CIMIS_RECORD_CAP+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, expected: bool) -> None:+ response = mock.Mock(spec=requests.Response)+ response.status_code = status+ session = mock.Mock()+ session.get.return_value = response++ with mock.patch.object(cimis, "make_tracked_session", return_value=session):+ ok, _msg = validate_credentials("appkey", ["2"], mock.Mock())+ assert ok is expected++ def test_unreachable_api_is_not_valid(self) -> None:+ session = mock.Mock()+ session.get.side_effect = requests.ConnectionError("boom")+ with mock.patch.object(cimis, "make_tracked_session", return_value=session):+ ok, msg = validate_credentials("appkey", [], mock.Mock())+ assert ok is False+ assert msg is not None+++class TestCimisSourceResponse:+ @parameterized.expand(+ [+ ("daily_data", ["Station", "Date"], "datetime"),+ ("hourly_data", ["Station", "Date", "Hour"], "datetime"),+ ("stations", ["StationNbr"], None),+ ("station_zipcodes", ["StationNbr", "ZipCode"], None),+ ("spatial_zipcodes", ["ZipCode"], None),+ ]+ )+ def test_source_response_shape(self, endpoint: str, primary_keys: list[str], partition_mode: str | None) -> None:+ response = cimis_source(endpoint=endpoint, app_key="k", targets=["2"], unit_of_measure="E", logger=mock.Mock())+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_mode == partition_mode+ assert response.sort_mode == "asc"+ if partition_mode == "datetime":+ assert response.partition_keys == [CIMIS_ENDPOINTS[endpoint].partition_key]+ assert response.partition_format == "month"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis_source.pynew file mode 100644index 000000000000..8c216427631c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cimis/tests/test_cimis_source.py@@ -0,0 +1,145 @@+from typing import Any, Literal++from unittest import mock++import requests+from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.cimis import cimis+from products.warehouse_sources.backend.temporal.data_imports.sources.cimis.source import CimisSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CimisSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(app_key: str = "key", targets: str | None = "2", unit: Literal["E", "M"] = "E") -> CimisSourceConfig:+ return CimisSourceConfig(app_key=app_key, targets=targets, unit_of_measure=unit)+++class TestCimisSourceConfig:+ def test_source_type(self) -> None:+ assert CimisSource().source_type == ExternalDataSourceType.CIMIS++ def test_source_config_metadata(self) -> None:+ config = CimisSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.ANALYTICS+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cimis"++ def test_source_config_fields(self) -> None:+ fields = {f.name: f for f in CimisSource().get_source_config.fields}+ assert set(fields) == {"app_key", "targets", "unit_of_measure"}+ app_key = fields["app_key"]+ targets = fields["targets"]+ assert isinstance(app_key, SourceFieldInputConfig)+ assert isinstance(targets, SourceFieldInputConfig)+ # The credential must be flagged secret so the serializer treats it as sensitive.+ assert app_key.required is True+ assert app_key.secret is True+ # Targets is optional so the metadata tables can sync without it.+ assert targets.required is False+++class TestCimisGetSchemas:+ def test_returns_all_endpoints(self) -> None:+ schemas = CimisSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == {+ "stations",+ "station_zipcodes",+ "spatial_zipcodes",+ "daily_data",+ "hourly_data",+ }++ def test_filters_by_names(self) -> None:+ schemas = CimisSource().get_schemas(_config(), team_id=1, names=["stations"])+ assert [s.name for s in schemas] == ["stations"]++ @parameterized.expand(+ [+ ("daily_data", True),+ ("hourly_data", True),+ ("stations", False),+ ("station_zipcodes", False),+ ("spatial_zipcodes", False),+ ]+ )+ def test_incremental_support(self, endpoint: str, supports_incremental: bool) -> None:+ schema = next(s for s in CimisSource().get_schemas(_config(), team_id=1) if s.name == endpoint)+ assert schema.supports_incremental is supports_incremental+ if supports_incremental:+ assert [f["field"] for f in schema.incremental_fields] == ["Date"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O), so the docs table catalog should render.+ tables = CimisSource().get_documented_tables()+ assert {t["name"] for t in tables} == {+ "stations",+ "station_zipcodes",+ "spatial_zipcodes",+ "daily_data",+ "hourly_data",+ }+++class TestCimisValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("bad", 403, False)])+ def test_validate_credentials(self, _name: str, status: int, expected: bool) -> None:+ response = mock.Mock(spec=requests.Response)+ response.status_code = status+ session = mock.Mock()+ session.get.return_value = response+ with mock.patch.object(cimis, "make_tracked_session", return_value=session):+ ok, _msg = CimisSource().validate_credentials(_config(), team_id=1)+ assert ok is expected+++class TestCimisNonRetryableErrors:+ def test_marks_auth_errors_non_retryable(self) -> None:+ errors = CimisSource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)+++class TestCimisSourceForPipeline:+ def test_plumbs_config_and_inputs_into_source_response(self) -> None:+ inputs = mock.Mock()+ inputs.schema_name = "daily_data"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2023-01-01"+ inputs.logger = mock.Mock()++ captured: dict[str, Any] = {}++ def fake_source(**kwargs: Any) -> str:+ captured.update(kwargs)+ return "response"++ with mock.patch.object(cimis, "cimis_source"):+ from products.warehouse_sources.backend.temporal.data_imports.sources.cimis import source as source_mod++ with mock.patch.object(source_mod, "cimis_source", side_effect=fake_source):+ source_mod.CimisSource().source_for_pipeline(_config(targets="2,8"), inputs)++ assert captured["endpoint"] == "daily_data"+ assert captured["app_key"] == "key"+ assert captured["targets"] == ["2", "8"]+ assert captured["should_use_incremental_field"] is True+ assert captured["db_incremental_field_last_value"] == "2023-01-01"++ def test_incremental_value_dropped_when_not_incremental(self) -> None:+ inputs = mock.Mock()+ inputs.schema_name = "stations"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2023-01-01"+ inputs.logger = mock.Mock()++ captured: dict[str, Any] = {}+ from products.warehouse_sources.backend.temporal.data_imports.sources.cimis import source as source_mod++ with mock.patch.object(source_mod, "cimis_source", side_effect=lambda **kw: captured.update(kw)):+ source_mod.CimisSource().source_for_pipeline(_config(), inputs)++ assert captured["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex fa7b8886ecad..d6203361883e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -639,7 +639,9 @@ class ChurnkeySourceConfig(config.Config):@config.configclass CimisSourceConfig(config.Config):- pass+ app_key: str+ targets: str | None = None+ unit_of_measure: Literal["E", "M"] | None = config.value(default="E")@config.config