Skip to content

: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.

feat(data-warehouse): implement openaq import source (#67812)

Tom Owers10ae4523c625
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index cf32d4e500e0..2f8692fc1660 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -221,6 +221,7 @@ the row lists both.
| onfleet | HTTP (cursor pagination) | requests | ✅ |
| open_exchange_rates | HTTP | requests | ✅ |
| orb | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| openaq | HTTP | requests | ✅ |
| openweather | HTTP | requests | ✅ |
| ortto | HTTP | requests | ✅ |
| oura | HTTP | requests | ✅ |
@@ -546,7 +547,6 @@ doesn't conflict with concurrent PRs.
- onepagecrm
- onesignal
- open_data_dc
-- openaq
- openfda
- opinion_stage
- opsgenie
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index c7b7593ba544..dfd7e5fb41b5 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
@@ -2238,7 +2238,7 @@ class OpenAIAdsSourceConfig(config.Config):
@config.config
class OpenAQSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/canonical_descriptions.py
new file mode 100644
index 000000000000..3dba9080a92a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/canonical_descriptions.py
@@ -0,0 +1,171 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "locations": {
+ "description": "Monitoring locations (stations) that report air-quality measurements.",
+ "docs_url": "https://docs.openaq.org/resources/locations",
+ "columns": {
+ "id": "Unique identifier for the location.",
+ "name": "Human-readable name of the location.",
+ "locality": "City or locality the location sits in.",
+ "timezone": "IANA timezone identifier for the location.",
+ "country": "Country the location belongs to.",
+ "owner": "Entity that owns the location.",
+ "provider": "Data provider that supplies the location's measurements.",
+ "isMobile": "Whether the location is a mobile (moving) monitor.",
+ "isMonitor": "Whether the location is a reference-grade monitor (vs a low-cost sensor).",
+ "instruments": "Instruments installed at the location.",
+ "sensors": "Sensors at the location, one per measured parameter.",
+ "coordinates": "Latitude/longitude of the location.",
+ "datetimeFirst": "Timestamp of the first measurement recorded at the location.",
+ "datetimeLast": "Timestamp of the most recent measurement recorded at the location.",
+ },
+ },
+ "parameters": {
+ "description": "Pollutants and other parameters measured across the network (e.g. PM2.5, O3, NO2).",
+ "docs_url": "https://docs.openaq.org/resources/parameters",
+ "columns": {
+ "id": "Unique identifier for the parameter.",
+ "name": "Short parameter code (e.g. pm25, o3, no2).",
+ "units": "Unit the parameter is reported in (e.g. µg/m³, ppm).",
+ "displayName": "Human-readable parameter name.",
+ "description": "Longer description of the parameter.",
+ },
+ },
+ "countries": {
+ "description": "Countries with at least one monitoring location in the network.",
+ "docs_url": "https://docs.openaq.org/resources/countries",
+ "columns": {
+ "id": "Unique identifier for the country.",
+ "code": "ISO 3166-1 alpha-2 country code.",
+ "name": "Country name.",
+ "parameters": "Parameters measured somewhere in the country.",
+ "datetimeFirst": "Timestamp of the first measurement recorded in the country.",
+ "datetimeLast": "Timestamp of the most recent measurement recorded in the country.",
+ },
+ },
+ "providers": {
+ "description": "Organizations that supply air-quality data to OpenAQ.",
+ "docs_url": "https://docs.openaq.org/resources/providers",
+ "columns": {
+ "id": "Unique identifier for the provider.",
+ "name": "Provider name.",
+ "sourceName": "Underlying source name for the provider.",
+ "datetimeAdded": "When the provider was added to OpenAQ.",
+ "datetimeFirst": "Timestamp of the provider's first measurement.",
+ "datetimeLast": "Timestamp of the provider's most recent measurement.",
+ "parameters": "Parameters the provider supplies.",
+ },
+ },
+ "instruments": {
+ "description": "Instrument models used by monitoring locations.",
+ "docs_url": "https://docs.openaq.org/resources/instruments",
+ "columns": {
+ "id": "Unique identifier for the instrument.",
+ "name": "Instrument model name.",
+ "isMonitor": "Whether the instrument is a reference-grade monitor.",
+ "manufacturer": "Manufacturer of the instrument.",
+ },
+ },
+ "manufacturers": {
+ "description": "Manufacturers of the instruments used across the network.",
+ "docs_url": "https://docs.openaq.org/resources/manufacturers",
+ "columns": {
+ "id": "Unique identifier for the manufacturer.",
+ "name": "Manufacturer name.",
+ "instruments": "Instruments produced by the manufacturer.",
+ },
+ },
+ "owners": {
+ "description": "Entities that own monitoring locations.",
+ "docs_url": "https://docs.openaq.org/resources/owners",
+ "columns": {
+ "id": "Unique identifier for the owner.",
+ "name": "Owner name.",
+ },
+ },
+ "licenses": {
+ "description": "Data licenses that govern how each provider's data may be used.",
+ "docs_url": "https://docs.openaq.org/resources/licenses",
+ "columns": {
+ "id": "Unique identifier for the license.",
+ "name": "License name.",
+ "commercialUseAllowed": "Whether commercial use is permitted.",
+ "attributionRequired": "Whether attribution is required.",
+ "shareAlikeRequired": "Whether derivative works must be shared under the same license.",
+ "modificationAllowed": "Whether the data may be modified.",
+ "redistributionAllowed": "Whether the data may be redistributed.",
+ "sourceUrl": "URL of the full license text.",
+ },
+ },
+ "sensors": {
+ "description": "Individual sensors, each measuring one parameter at one location. Materialized from the embedded sensor list on each location.",
+ "docs_url": "https://docs.openaq.org/resources/sensors",
+ "columns": {
+ "id": "Unique identifier for the sensor.",
+ "name": "Sensor name.",
+ "parameter_id": "Identifier of the parameter this sensor measures.",
+ "parameter_name": "Short code of the parameter this sensor measures.",
+ "parameter_units": "Unit the sensor's measurements are reported in.",
+ "location_id": "Identifier of the location the sensor belongs to.",
+ "location_name": "Name of the location the sensor belongs to.",
+ "timezone": "IANA timezone of the sensor's location.",
+ "coordinates": "Latitude/longitude of the sensor's location.",
+ "country": "Country the sensor's location belongs to.",
+ "provider": "Data provider for the sensor's location.",
+ },
+ },
+ "measurements": {
+ "description": "Raw measurements reported by each sensor, one row per sensor per reporting period.",
+ "docs_url": "https://docs.openaq.org/resources/measurements",
+ "columns": {
+ "sensor_id": "Identifier of the sensor that produced the measurement.",
+ "datetime_from": "UTC start of the measurement's reporting period (exclusive time-ending convention).",
+ "datetime_to": "UTC end of the measurement's reporting period.",
+ "value": "Measured value in the parameter's units.",
+ "parameter_id": "Identifier of the measured parameter.",
+ "parameter_name": "Short code of the measured parameter.",
+ "parameter_units": "Unit the value is reported in.",
+ "coordinates": "Latitude/longitude of the sensor's location.",
+ "coverage": "Data-coverage summary for the period.",
+ "summary": "Statistical summary of the readings in the measurement period.",
+ "flag_info": "Quality/flag information for the measurement.",
+ },
+ },
+ "measurements_hourly": {
+ "description": "Hourly aggregated measurements per sensor.",
+ "docs_url": "https://docs.openaq.org/resources/measurements",
+ "columns": {
+ "sensor_id": "Identifier of the sensor that produced the measurement.",
+ "datetime_from": "UTC start of the hourly period.",
+ "datetime_to": "UTC end of the hourly period.",
+ "value": "Aggregated value for the hour, in the parameter's units.",
+ "parameter_id": "Identifier of the measured parameter.",
+ "parameter_name": "Short code of the measured parameter.",
+ "parameter_units": "Unit the value is reported in.",
+ "coordinates": "Latitude/longitude of the sensor's location.",
+ "summary": "Statistical summary of the readings aggregated into the hour.",
+ "coverage": "Data-coverage summary for the hour.",
+ "flag_info": "Quality/flag information for the aggregated measurement.",
+ },
+ },
+ "measurements_daily": {
+ "description": "Daily aggregated measurements per sensor.",
+ "docs_url": "https://docs.openaq.org/resources/measurements",
+ "columns": {
+ "sensor_id": "Identifier of the sensor that produced the measurement.",
+ "datetime_from": "UTC start of the daily period.",
+ "datetime_to": "UTC end of the daily period.",
+ "value": "Aggregated value for the day, in the parameter's units.",
+ "parameter_id": "Identifier of the measured parameter.",
+ "parameter_name": "Short code of the measured parameter.",
+ "parameter_units": "Unit the value is reported in.",
+ "coordinates": "Latitude/longitude of the sensor's location.",
+ "summary": "Statistical summary of the readings aggregated into the day.",
+ "coverage": "Data-coverage summary for the day.",
+ "flag_info": "Quality/flag information for the aggregated measurement.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/openaq.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/openaq.py
new file mode 100644
index 000000000000..b09eea31473d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/openaq.py
@@ -0,0 +1,367 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+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.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.openaq.settings import (
+ OPENAQ_ENDPOINTS,
+ OpenAQEndpointConfig,
+)
+
+OPENAQ_BASE_URL = "https://api.openaq.org"
+
+# The v3 API caps page size at 1000 and rejects requests where page * limit exceeds 100_000
+# (offset ceiling). We page in 1000s and stop each per-sensor fan-out at MAX_PAGES so we never
+# cross that ceiling; ascending order + the incremental datetime filter means a truncated sensor
+# resumes from its last synced value on the next sync rather than losing data.
+OPENAQ_PAGE_SIZE: int = 1000
+MAX_PAGES: int = 100
+
+# The only sort field every v3 list endpoint accepts is `id`; sorting ascending gives page-stable
+# pagination for the full-refresh reference tables.
+_LIST_SORT_PARAMS = {"order_by": "id", "sort_order": "asc"}
+
+
+class OpenAQRetryableError(Exception):
+ pass
+
+
+class OpenAQResumeConfig:
+ # Next page to fetch (1-based). For list/sensors endpoints this pages the top-level resource;
+ # for measurement fan-out it's the page within `parent_sensor_id`.
+ page: int = 1
+ # The sensor currently being fetched in a measurement fan-out. A stable sensor-id bookmark (not a
+ # positional index) so sensors added/removed between a crash and the retry can't resume us into the
+ # wrong sensor. None for list/sensors endpoints.
+ parent_sensor_id: int | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {"X-API-Key": api_key, "Accept": "application/json"}
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ if not params:
+ return base_url
+ return f"{base_url}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str) -> bool:
+ # /v3/parameters is a small reference list reachable by any valid key, so it's the cheapest
+ # probe that the token itself is genuine.
+ url = _build_url(f"{OPENAQ_BASE_URL}/v3/parameters", {"limit": 1})
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ OpenAQRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(6),
+ wait=wait_exponential_jitter(initial=2, max=60),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # Free-tier keys are limited to 60 req/min and 2000 req/hour; a 429 carries X-RateLimit-Reset
+ # headers we could honor exactly, but exponential backoff keeps this simple and correct.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise OpenAQRetryableError(f"OpenAQ API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"OpenAQ API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _format_time_value(value: Any, prefix: str) -> str:
+ """Format an incremental cursor value for the OpenAQ measurement time filter.
+
+ The raw/hourly endpoints take an ISO-8601 datetime (`datetime_from`); the daily/yearly
+ aggregates take a calendar date (`date_from`).
+ """
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if prefix == "date":
+ return aware.date().isoformat()
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return value.isoformat() if prefix == "date" else f"{value.isoformat()}T00:00:00Z"
+ return str(value)
+
+
+def _flatten_sensor(location: dict[str, Any], sensor: dict[str, Any]) -> dict[str, Any]:
+ """Shape one embedded location sensor into a flat row with its parent-location context."""
+ parameter = sensor.get("parameter") or {}
+ return {
+ # Direct access on the primary key so a malformed row fails fast rather than merging
+ # every id-less sensor into one null-keyed row.
+ "id": sensor["id"],
+ "name": sensor.get("name"),
+ "parameter_id": parameter.get("id"),
+ "parameter_name": parameter.get("name"),
+ "parameter_units": parameter.get("units"),
+ "parameter_display_name": parameter.get("displayName"),
+ "location_id": location.get("id"),
+ "location_name": location.get("name"),
+ "locality": location.get("locality"),
+ "timezone": location.get("timezone"),
+ "coordinates": location.get("coordinates"),
+ "country": location.get("country"),
+ "provider": location.get("provider"),
+ }
+
+
+def _flatten_measurement(item: dict[str, Any], sensor_id: int) -> dict[str, Any]:
+ """Shape one measurement into a flat row keyed by (sensor_id, period start).
+
+ A measurement carries no id of its own; its period start (`datetime_from`) plus the sensor it
+ belongs to uniquely identify it, so both are lifted to the top level for the primary key.
+ """
+ period = item.get("period") or {}
+ datetime_from = (period.get("datetimeFrom") or {}).get("utc")
+ datetime_to = (period.get("datetimeTo") or {}).get("utc")
+ parameter = item.get("parameter") or {}
+ return {
+ "sensor_id": sensor_id,
+ "datetime_from": datetime_from,
+ "datetime_to": datetime_to,
+ "value": item.get("value"),
+ "parameter_id": parameter.get("id"),
+ "parameter_name": parameter.get("name"),
+ "parameter_units": parameter.get("units"),
+ "coordinates": item.get("coordinates"),
+ "coverage": item.get("coverage"),
+ "summary": item.get("summary"),
+ "flag_info": item.get("flagInfo"),
+ }
+
+
+def _iter_location_pages(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger, start_page: int = 1
+) -> Iterator[tuple[int, list[dict[str, Any]], bool]]:
+ """Page through /v3/locations, yielding (page, locations, is_last_page)."""
+ page = start_page
+ while True:
+ params = {**_LIST_SORT_PARAMS, "limit": OPENAQ_PAGE_SIZE, "page": page}
+ data = _fetch_page(session, _build_url(f"{OPENAQ_BASE_URL}/v3/locations", params), headers, logger)
+ results = data.get("results", [])
+ is_last = len(results) < OPENAQ_PAGE_SIZE or page >= MAX_PAGES
+ if page >= MAX_PAGES and len(results) == OPENAQ_PAGE_SIZE:
+ logger.warning(f"OpenAQ: hit MAX_PAGES={MAX_PAGES} paging /v3/locations; stopping enumeration")
+ yield page, results, is_last
+ if is_last:
+ break
+ page += 1
+
+
+def _iter_sensor_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[int]:
+ """Walk /v3/locations once and yield each embedded sensor id (globally unique)."""
+ for _page, locations, _is_last in _iter_location_pages(session, headers, logger):
+ for location in locations:
+ for sensor in location.get("sensors") or []:
+ sensor_id = sensor.get("id")
+ if sensor_id is not None:
+ yield sensor_id
+
+
+def _get_list_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ config: OpenAQEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[OpenAQResumeConfig],
+) -> Iterator[Any]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume else 1
+
+ while page <= MAX_PAGES:
+ params = {**_LIST_SORT_PARAMS, "limit": OPENAQ_PAGE_SIZE, "page": page}
+ data = _fetch_page(session, _build_url(f"{OPENAQ_BASE_URL}{config.path}", params), headers, logger)
+ results = data.get("results", [])
+ is_last = len(results) < OPENAQ_PAGE_SIZE
+
+ for item in results:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if not is_last:
+ resumable_source_manager.save_state(OpenAQResumeConfig(page=page + 1))
+
+ if is_last:
+ break
+ page += 1
+
+
+def _get_sensor_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[OpenAQResumeConfig],
+) -> Iterator[Any]:
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start_page = resume.page if resume else 1
+
+ for page, locations, is_last in _iter_location_pages(session, headers, logger, start_page):
+ for location in locations:
+ for sensor in location.get("sensors") or []:
+ batcher.batch(_flatten_sensor(location, sensor))
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if not is_last:
+ resumable_source_manager.save_state(OpenAQResumeConfig(page=page + 1))
+
+
+def _get_measurement_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ config: OpenAQEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[OpenAQResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[Any]:
+ sensor_ids = list(_iter_sensor_ids(session, headers, logger))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = sensor_ids
+ resume_page = 1
+ if resume is not None and resume.parent_sensor_id is not None and resume.parent_sensor_id in sensor_ids:
+ remaining = sensor_ids[sensor_ids.index(resume.parent_sensor_id) :]
+ resume_page = resume.page
+ logger.debug(f"OpenAQ: resuming {config.name} from sensor_id={resume.parent_sensor_id}, page={resume_page}")
+
+ if config.time_param_prefix is None:
+ raise ValueError(f"OpenAQ endpoint {config.name!r} has kind='measurement' but no time_param_prefix")
+ time_params: dict[str, Any] = {}
+ if should_use_incremental_field and db_incremental_field_last_value:
+ time_params[f"{config.time_param_prefix}_from"] = _format_time_value(
+ db_incremental_field_last_value, config.time_param_prefix
+ )
+
+ for index, sensor_id in enumerate(remaining):
+ page = resume_page if index == 0 else 1
+ resume_page = 1 # only the resumed-into sensor uses the saved page; the rest start fresh
+
+ while page <= MAX_PAGES:
+ params = {**time_params, "limit": OPENAQ_PAGE_SIZE, "page": page}
+ path = config.path.format(sensors_id=sensor_id)
+ data = _fetch_page(session, _build_url(f"{OPENAQ_BASE_URL}{path}", params), headers, logger)
+ results = data.get("results", [])
+ is_last = len(results) < OPENAQ_PAGE_SIZE or page >= MAX_PAGES
+ if page >= MAX_PAGES and len(results) == OPENAQ_PAGE_SIZE:
+ logger.warning(
+ f"OpenAQ: hit MAX_PAGES={MAX_PAGES} for {config.name} sensor_id={sensor_id}; "
+ "remaining rows sync on the next incremental run"
+ )
+
+ for item in results:
+ batcher.batch(_flatten_measurement(item, sensor_id))
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if not is_last:
+ resumable_source_manager.save_state(
+ OpenAQResumeConfig(page=page + 1, parent_sensor_id=sensor_id)
+ )
+
+ if is_last:
+ break
+ page += 1
+
+ # Advance the bookmark to the next sensor so a crash between sensors resumes correctly.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(OpenAQResumeConfig(page=1, parent_sensor_id=remaining[index + 1]))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpenAQResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = OPENAQ_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # One session reused across every page (and every sensor, for fan-out) so urllib3 keeps the
+ # connection alive instead of re-handshaking per request. Redact the key so it never lands in
+ # logged URLs or captured samples.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ if config.kind == "list":
+ yield from _get_list_rows(session, headers, logger, batcher, config, resumable_source_manager)
+ elif config.kind == "sensors":
+ yield from _get_sensor_rows(session, headers, logger, batcher, resumable_source_manager)
+ else:
+ yield from _get_measurement_rows(
+ session,
+ headers,
+ logger,
+ batcher,
+ config,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def openaq_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpenAQResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = OPENAQ_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ 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,
+ # Measurements come back oldest-first (ascending period start) per the v3 docs, which the
+ # incremental watermark relies on. Unverified against the live API (no key available); noted
+ # in the PR. If this proves wrong, the datetime_from server filter still bounds each fetch, so
+ # completeness holds — only mid-sync watermark checkpointing would need sort_mode="desc".
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/settings.py
new file mode 100644
index 000000000000..82c72c4367d9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/settings.py
@@ -0,0 +1,90 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# How an endpoint is fetched:
+# - "list": a top-level paginated list (e.g. /v3/locations). Full refresh.
+# - "sensors": derived by walking /v3/locations and flattening each location's embedded
+# `sensors` array into one row per sensor. Full refresh (single locations walk, cheap).
+# - "measurement": fanned out per sensor (/v3/sensors/{sensors_id}/...). Incremental via the
+# API's server-side datetime filter. Request-heavy (one paginated fetch per sensor), so opt-in.
+EndpointKind = Literal["list", "sensors", "measurement"]
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class OpenAQEndpointConfig:
+ name: str
+ kind: EndpointKind
+ # API path. For "measurement" endpoints this is a template with a `{sensors_id}` placeholder.
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Query-param prefix for the measurement time filter. The raw + hourly endpoints use
+ # `datetime_from`/`datetime_to`; the daily + yearly aggregates use `date_from`/`date_to`.
+ time_param_prefix: Optional[str] = None
+ should_sync_default: bool = True
+
+
+OPENAQ_ENDPOINTS: dict[str, OpenAQEndpointConfig] = {
+ "locations": OpenAQEndpointConfig(name="locations", kind="list", path="/v3/locations"),
+ "parameters": OpenAQEndpointConfig(name="parameters", kind="list", path="/v3/parameters"),
+ "countries": OpenAQEndpointConfig(name="countries", kind="list", path="/v3/countries"),
+ "providers": OpenAQEndpointConfig(name="providers", kind="list", path="/v3/providers"),
+ "instruments": OpenAQEndpointConfig(name="instruments", kind="list", path="/v3/instruments"),
+ "manufacturers": OpenAQEndpointConfig(name="manufacturers", kind="list", path="/v3/manufacturers"),
+ "owners": OpenAQEndpointConfig(name="owners", kind="list", path="/v3/owners"),
+ "licenses": OpenAQEndpointConfig(name="licenses", kind="list", path="/v3/licenses"),
+ # Sensors have no top-level list endpoint, so we materialize them from the embedded
+ # `sensors` array on each location. Sensor ids are globally unique, so ["id"] is table-wide unique.
+ "sensors": OpenAQEndpointConfig(name="sensors", kind="sensors", path="/v3/locations"),
+ # Per-sensor measurement streams. A measurement has no id of its own, so the primary key is
+ # (sensor_id, period start). Partition/incremental on `datetime_from` — the reading's period
+ # start, a stable time-ending value that never shifts once written.
+ "measurements": OpenAQEndpointConfig(
+ name="measurements",
+ kind="measurement",
+ path="/v3/sensors/{sensors_id}/measurements",
+ primary_keys=["sensor_id", "datetime_from"],
+ partition_key="datetime_from",
+ incremental_fields=[_datetime_incremental_field("datetime_from")],
+ time_param_prefix="datetime",
+ should_sync_default=False,
+ ),
+ "measurements_hourly": OpenAQEndpointConfig(
+ name="measurements_hourly",
+ kind="measurement",
+ path="/v3/sensors/{sensors_id}/hours",
+ primary_keys=["sensor_id", "datetime_from"],
+ partition_key="datetime_from",
+ incremental_fields=[_datetime_incremental_field("datetime_from")],
+ time_param_prefix="datetime",
+ should_sync_default=False,
+ ),
+ "measurements_daily": OpenAQEndpointConfig(
+ name="measurements_daily",
+ kind="measurement",
+ path="/v3/sensors/{sensors_id}/days",
+ primary_keys=["sensor_id", "datetime_from"],
+ partition_key="datetime_from",
+ incremental_fields=[_datetime_incremental_field("datetime_from")],
+ time_param_prefix="date",
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(OPENAQ_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in OPENAQ_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/source.py
index c8061b8e8403..de92bfb6774e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OpenAQSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.openaq.openaq import (
+ OpenAQResumeConfig,
+ openaq_source,
+ validate_credentials as validate_openaq_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openaq.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ OPENAQ_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class OpenAQSource(SimpleSource[OpenAQSourceConfig]):
+class OpenAQSource(ResumableSource[OpenAQSourceConfig, OpenAQResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.OPENAQ
@@ -24,7 +48,104 @@ class OpenAQSource(SimpleSource[OpenAQSourceConfig]):
name=SchemaExternalDataSourceType.OPEN_AQ,
category=DataWarehouseSourceCategory.ANALYTICS,
label="OpenAQ",
- iconPath="/static/services/openaq.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your OpenAQ API key to pull global air-quality data into the PostHog Data warehouse.
+
+You can create a free API key from your [OpenAQ Explorer account](https://explore.openaq.org/account).
+
+The free tier is limited to 60 requests per minute. The measurement tables fetch data per sensor, so syncing them against a broad set of locations makes many requests — they're off by default; enable only the sensors you need.""",
+ iconPath="/static/services/openaq.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/openaq",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.openaq.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.
+ # Retrying can never satisfy a credential problem, so stop the sync. Match the stable status
+ # text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.openaq.org": "Your OpenAQ API key is invalid or has been revoked. Create a new key in your OpenAQ account, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.openaq.org": "Your OpenAQ API key does not have access to this data. Check the key in your OpenAQ account, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: OpenAQSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "sensors":
+ return "Sensors materialized from each location's embedded sensor list. Full refresh only"
+ if OPENAQ_ENDPOINTS[endpoint].kind == "measurement":
+ return "Fetched per sensor across all locations — request-heavy, so off by default"
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = OPENAQ_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,
+ detected_primary_keys=endpoint_config.primary_keys,
+ description=_description(endpoint),
+ )
+
+ 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: OpenAQSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_openaq_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid OpenAQ API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenAQResumeConfig]:
+ return ResumableSourceManager[OpenAQResumeConfig](inputs, OpenAQResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OpenAQSourceConfig,
+ resumable_source_manager: ResumableSourceManager[OpenAQResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return openaq_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ 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/openaq/tests/test_openaq.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/tests/test_openaq.py
new file mode 100644
index 000000000000..3af842389e43
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/tests/test_openaq.py
@@ -0,0 +1,293 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.openaq import openaq
+from products.warehouse_sources.backend.temporal.data_imports.sources.openaq.openaq import (
+ OpenAQResumeConfig,
+ _build_url,
+ _flatten_measurement,
+ _flatten_sensor,
+ _format_time_value,
+ get_rows,
+ validate_credentials,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: OpenAQResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[OpenAQResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> OpenAQResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: OpenAQResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], endpoint: str, **kwargs
+) -> list[dict]:
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ result = pages[url]
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+ monkeypatch.setattr(openaq, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for table in get_rows(
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestFormatTimeValue:
+ @parameterized.expand(
+ [
+ ("datetime_prefix_utc", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "datetime", "2026-03-04T02:58:14Z"),
+ ("datetime_prefix_naive", datetime(2026, 3, 4, 2, 58, 14), "datetime", "2026-03-04T02:58:14Z"),
+ ("date_prefix_from_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "date", "2026-03-04"),
+ ("date_prefix_from_date", date(2026, 3, 4), "date", "2026-03-04"),
+ ("datetime_prefix_from_date", date(2026, 3, 4), "datetime", "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "2026-03-04T00:00:00Z", "datetime", "2026-03-04T00:00:00Z"),
+ ]
+ )
+ def test_format_time_value(self, _name: str, value: Any, prefix: str, expected: str) -> None:
+ # A wrong format 400s the measurement endpoint or silently drops the incremental filter.
+ assert _format_time_value(value, prefix) == expected
+
+
+class TestFlattenMeasurement:
+ def test_lifts_sensor_id_and_period_start_for_primary_key(self) -> None:
+ # The (sensor_id, datetime_from) pair is the composite primary key; both must reach the top level.
+ item = {
+ "value": 12.3,
+ "parameter": {"id": 2, "name": "pm25", "units": "µg/m³"},
+ "period": {
+ "datetimeFrom": {"utc": "2026-01-01T00:00:00Z", "local": "2026-01-01T00:00:00+00:00"},
+ "datetimeTo": {"utc": "2026-01-01T01:00:00Z"},
+ },
+ "coverage": {"percentComplete": 100},
+ "flagInfo": {"hasFlags": False},
+ }
+ row = _flatten_measurement(item, sensor_id=99)
+ assert row["sensor_id"] == 99
+ assert row["datetime_from"] == "2026-01-01T00:00:00Z"
+ assert row["datetime_to"] == "2026-01-01T01:00:00Z"
+ assert row["value"] == 12.3
+ assert row["parameter_id"] == 2
+ assert row["parameter_name"] == "pm25"
+
+ @parameterized.expand(
+ [
+ ("missing_period", {"value": 1.0}),
+ ("null_period", {"value": 1.0, "period": None}),
+ ("period_without_datetime", {"value": 1.0, "period": {"label": "x"}}),
+ ]
+ )
+ def test_missing_period_yields_null_datetime_not_crash(self, _name: str, item: dict) -> None:
+ # A sensor with a sparse/absent period must not blow up the whole fan-out.
+ row = _flatten_measurement(item, sensor_id=1)
+ assert row["sensor_id"] == 1
+ assert row["datetime_from"] is None
+
+
+class TestFlattenSensor:
+ def test_attaches_location_context_and_flattens_parameter(self) -> None:
+ location = {"id": 7, "name": "Station A", "timezone": "UTC", "country": {"code": "US"}}
+ sensor = {"id": 55, "name": "pm25 sensor", "parameter": {"id": 2, "name": "pm25", "units": "µg/m³"}}
+ row = _flatten_sensor(location, sensor)
+ assert row["id"] == 55
+ assert row["location_id"] == 7
+ assert row["parameter_name"] == "pm25"
+ assert row["timezone"] == "UTC"
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("server_error", 500, False)])
+ def test_validate_credentials_maps_status(self, _name: str, status: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(openaq, "make_tracked_session", return_value=session):
+ assert validate_credentials("key") is expected
+
+ def test_validate_credentials_swallows_transport_error(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(openaq, "make_tracked_session", return_value=session):
+ assert validate_credentials("key") is False
+
+
+class TestFetchPageRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_statuses_retry_then_succeed(self, _name: str, status: int) -> None:
+ bad = MagicMock()
+ bad.status_code = status
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = {"results": []}
+
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(openaq._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = openaq._fetch_page(session, "https://api.openaq.org/v3/parameters", {}, MagicMock())
+
+ assert result == {"results": []}
+ assert session.get.call_count == 2
+
+ def test_client_error_raises_and_does_not_retry(self) -> None:
+ error_response = requests.Response()
+ error_response.status_code = 401
+ response = MagicMock()
+ response.status_code = 401
+ response.ok = False
+ response.raise_for_status.side_effect = requests.HTTPError(
+ "401 Client Error: Unauthorized", response=error_response
+ )
+
+ session = MagicMock()
+ session.get.return_value = response
+
+ with patch.object(openaq._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(requests.HTTPError):
+ openaq._fetch_page(session, "https://api.openaq.org/v3/parameters", {}, MagicMock())
+
+ assert session.get.call_count == 1
+
+
+class TestListPagination:
+ def setup_method(self) -> None:
+ # Shrink the page size so a 2-item first page forces a second fetch.
+ self._orig = openaq.OPENAQ_PAGE_SIZE
+ openaq.OPENAQ_PAGE_SIZE = 2
+
+ def teardown_method(self) -> None:
+ openaq.OPENAQ_PAGE_SIZE = self._orig
+
+ def _list_url(self, path: str, page: int) -> str:
+ params = {**openaq._LIST_SORT_PARAMS, "limit": openaq.OPENAQ_PAGE_SIZE, "page": page}
+ return _build_url(f"{openaq.OPENAQ_BASE_URL}{path}", params)
+
+ def test_pages_until_short_page_then_stops(self, monkeypatch: Any) -> None:
+ pages = {
+ self._list_url("/v3/parameters", 1): {"results": [{"id": 1}, {"id": 2}]},
+ self._list_url("/v3/parameters", 2): {"results": [{"id": 3}]},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, endpoint="parameters")
+ assert [r["id"] for r in rows] == [1, 2, 3]
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ pages = {
+ # Page 1 must never be fetched when resuming from page 2.
+ self._list_url("/v3/parameters", 2): {"results": [{"id": 3}]},
+ }
+ manager = _FakeResumableManager(OpenAQResumeConfig(page=2))
+ rows = _collect(manager, monkeypatch, pages, endpoint="parameters")
+ assert [r["id"] for r in rows] == [3]
+
+
+class TestSensorsFanOut:
+ def _loc_url(self, page: int) -> str:
+ params = {**openaq._LIST_SORT_PARAMS, "limit": openaq.OPENAQ_PAGE_SIZE, "page": page}
+ return _build_url(f"{openaq.OPENAQ_BASE_URL}/v3/locations", params)
+
+ def test_materializes_one_row_per_embedded_sensor(self, monkeypatch: Any) -> None:
+ pages = {
+ self._loc_url(1): {
+ "results": [
+ {"id": 1, "name": "L1", "sensors": [{"id": 10, "parameter": {"name": "pm25"}}]},
+ {"id": 2, "name": "L2", "sensors": [{"id": 20, "parameter": {"name": "o3"}}]},
+ ]
+ }
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, endpoint="sensors")
+ assert [(r["id"], r["location_id"], r["parameter_name"]) for r in rows] == [
+ (10, 1, "pm25"),
+ (20, 2, "o3"),
+ ]
+
+
+class TestMeasurementFanOut:
+ def _loc_url(self, page: int) -> str:
+ params = {**openaq._LIST_SORT_PARAMS, "limit": openaq.OPENAQ_PAGE_SIZE, "page": page}
+ return _build_url(f"{openaq.OPENAQ_BASE_URL}/v3/locations", params)
+
+ def _sensor_url(self, sensor_id: int, page: int, extra: dict | None = None) -> str:
+ params = {**(extra or {}), "limit": openaq.OPENAQ_PAGE_SIZE, "page": page}
+ return _build_url(f"{openaq.OPENAQ_BASE_URL}/v3/sensors/{sensor_id}/measurements", params)
+
+ def _measurement(self, dt: str, value: float) -> dict:
+ return {"value": value, "parameter": {"name": "pm25"}, "period": {"datetimeFrom": {"utc": dt}}}
+
+ def test_fans_out_over_every_sensor(self, monkeypatch: Any) -> None:
+ pages = {
+ self._loc_url(1): {
+ "results": [{"id": 1, "sensors": [{"id": 10}, {"id": 11}]}],
+ },
+ self._sensor_url(10, 1): {"results": [self._measurement("2026-01-01T00:00:00Z", 5.0)]},
+ self._sensor_url(11, 1): {"results": [self._measurement("2026-01-02T00:00:00Z", 6.0)]},
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, endpoint="measurements")
+ assert [(r["sensor_id"], r["datetime_from"], r["value"]) for r in rows] == [
+ (10, "2026-01-01T00:00:00Z", 5.0),
+ (11, "2026-01-02T00:00:00Z", 6.0),
+ ]
+
+ def test_applies_incremental_datetime_filter(self, monkeypatch: Any) -> None:
+ cutoff = datetime(2026, 1, 5, tzinfo=UTC)
+ filtered_url = self._sensor_url(10, 1, extra={"datetime_from": "2026-01-05T00:00:00Z"})
+ pages = {
+ self._loc_url(1): {"results": [{"id": 1, "sensors": [{"id": 10}]}]},
+ filtered_url: {"results": [self._measurement("2026-01-06T00:00:00Z", 7.0)]},
+ }
+ # The row is only reachable if the request carried datetime_from — proving the server-side filter is applied.
+ rows = _collect(
+ _FakeResumableManager(),
+ monkeypatch,
+ pages,
+ endpoint="measurements",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=cutoff,
+ )
+ assert [r["datetime_from"] for r in rows] == ["2026-01-06T00:00:00Z"]
+
+ def test_saves_bookmark_advancing_to_next_sensor(self, monkeypatch: Any) -> None:
+ pages = {
+ self._loc_url(1): {"results": [{"id": 1, "sensors": [{"id": 10}, {"id": 11}]}]},
+ self._sensor_url(10, 1): {"results": [self._measurement("2026-01-01T00:00:00Z", 5.0)]},
+ self._sensor_url(11, 1): {"results": [self._measurement("2026-01-02T00:00:00Z", 6.0)]},
+ }
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, pages, endpoint="measurements")
+ # After finishing sensor 10, the bookmark advances to sensor 11 so a crash resumes there.
+ assert OpenAQResumeConfig(page=1, parent_sensor_id=11) in manager.saved
+
+ def test_resume_skips_already_synced_sensors(self, monkeypatch: Any) -> None:
+ pages = {
+ self._loc_url(1): {"results": [{"id": 1, "sensors": [{"id": 10}, {"id": 11}]}]},
+ # Sensor 10 must not be fetched again; only sensor 11 (the bookmark) is.
+ self._sensor_url(11, 1): {"results": [self._measurement("2026-01-02T00:00:00Z", 6.0)]},
+ }
+ manager = _FakeResumableManager(OpenAQResumeConfig(page=1, parent_sensor_id=11))
+ rows = _collect(manager, monkeypatch, pages, endpoint="measurements")
+ assert [r["sensor_id"] for r in rows] == [11]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/tests/test_openaq_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/tests/test_openaq_source.py
new file mode 100644
index 000000000000..4ad0e858a3d6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openaq/tests/test_openaq_source.py
@@ -0,0 +1,167 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OpenAQSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.openaq.openaq import OpenAQResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.openaq.settings import OPENAQ_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.openaq.source import OpenAQSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> OpenAQSourceConfig:
+ return OpenAQSourceConfig(api_key="key")
+
+
+class TestOpenAQSourceConfig:
+ def test_source_type(self) -> None:
+ assert OpenAQSource().source_type == ExternalDataSourceType.OPENAQ
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ fields = OpenAQSource().get_source_config.fields
+ assert len(fields) == 1
+ api_key = fields[0]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.name == "api_key"
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.required is True
+ assert api_key.secret is True
+
+ def test_docs_url_matches_slug(self) -> None:
+ # The website derives the doc slug from this URL; a mismatch 404s the Supported tables section.
+ assert OpenAQSource().get_source_config.docsUrl == "https://posthog.com/docs/cdp/sources/openaq"
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog, so the public docs may render the table list.
+ assert OpenAQSource.lists_tables_without_credentials is True
+
+
+class TestOpenAQSchemas:
+ def test_all_endpoints_exposed(self) -> None:
+ names = {s.name for s in OpenAQSource().get_schemas(_config(), team_id=1)}
+ assert names == set(OPENAQ_ENDPOINTS.keys())
+
+ @parameterized.expand(
+ [
+ ("measurements", True, False),
+ ("measurements_hourly", True, False),
+ ("measurements_daily", True, False),
+ ("locations", False, True),
+ ("parameters", False, True),
+ ("sensors", False, True),
+ ]
+ )
+ def test_incremental_and_default_sync_flags(
+ self, endpoint: str, expected_incremental: bool, expected_default_sync: bool
+ ) -> None:
+ # Only the per-sensor measurement streams have a server-side datetime filter, so only they are
+ # incremental; and because they're request-heavy they must be off by default.
+ schema = {s.name: s for s in OpenAQSource().get_schemas(_config(), team_id=1)}[endpoint]
+ assert schema.supports_incremental is expected_incremental
+ assert schema.should_sync_default is expected_default_sync
+
+ def test_measurement_primary_key_is_sensor_and_period(self) -> None:
+ # A non-unique key seeds duplicate rows that every later merge multi-matches; measurements have
+ # no id of their own, so the key must be (sensor_id, datetime_from).
+ schema = {s.name: s for s in OpenAQSource().get_schemas(_config(), team_id=1)}["measurements"]
+ assert schema.detected_primary_keys == ["sensor_id", "datetime_from"]
+
+ def test_names_filter_narrows_schemas(self) -> None:
+ schemas = OpenAQSource().get_schemas(_config(), team_id=1, names=["parameters"])
+ assert [s.name for s in schemas] == ["parameters"]
+
+
+class TestOpenAQNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.openaq.org/v3/locations?page=1"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.openaq.org/v3/sensors/1/measurements"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ non_retryable = OpenAQSource().get_non_retryable_errors()
+ assert any(key in observed for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("rate_limit", "429 Client Error: Too Many Requests for url: https://api.openaq.org/v3/locations"),
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.openaq.org/v3/locations"),
+ ("timeout", "HTTPSConnectionPool(host='api.openaq.org', port=443): Read timed out."),
+ ]
+ )
+ def test_transient_errors_stay_retryable(self, _name: str, observed: str) -> None:
+ non_retryable = OpenAQSource().get_non_retryable_errors()
+ assert not any(key in observed for key in non_retryable)
+
+
+class TestOpenAQValidateCredentials:
+ @parameterized.expand([("valid", True), ("invalid", False)])
+ def test_validate_credentials(self, _name: str, upstream_ok: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.openaq.source.validate_openaq_credentials",
+ return_value=upstream_ok,
+ ):
+ valid, message = OpenAQSource().validate_credentials(_config(), team_id=1)
+ assert valid is upstream_ok
+ assert (message is None) is upstream_ok
+
+
+class TestOpenAQPipelineWiring:
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = OpenAQSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OpenAQResumeConfig
+
+ def _inputs(self, **overrides: Any) -> MagicMock:
+ inputs = MagicMock()
+ inputs.schema_name = overrides.get("schema_name", "measurements")
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = overrides.get("should_use_incremental_field", True)
+ inputs.db_incremental_field_last_value = overrides.get(
+ "db_incremental_field_last_value", "2026-01-01T00:00:00Z"
+ )
+ return inputs
+
+ def test_source_for_pipeline_passes_incremental_value_when_enabled(self) -> None:
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.openaq.source.openaq_source"
+ ) as mock_source:
+ OpenAQSource().source_for_pipeline(_config(), manager, self._inputs())
+ _, kwargs = mock_source.call_args
+ assert kwargs["endpoint"] == "measurements"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ def test_source_for_pipeline_drops_incremental_value_when_disabled(self) -> None:
+ # When the schema isn't synced incrementally, the last value must not leak into a filter.
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.openaq.source.openaq_source"
+ ) as mock_source:
+ OpenAQSource().source_for_pipeline(
+ _config(),
+ manager,
+ self._inputs(should_use_incremental_field=False),
+ )
+ _, kwargs = mock_source.call_args
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None
+
+
+class TestOpenAQDocumentedTables:
+ def test_documented_tables_include_curated_descriptions(self) -> None:
+ # lists_tables_without_credentials + canonical descriptions feed the public Supported tables docs.
+ tables = {t["name"]: t for t in OpenAQSource().get_documented_tables()}
+ assert set(tables) == set(OPENAQ_ENDPOINTS.keys())
+ # locations has no schema-level description, so the curated canonical one is surfaced.
+ assert tables["locations"]["description"].startswith("Monitoring locations")
+ assert "Incremental" in tables["measurements"]["sync_methods"]
+ assert "Full refresh" in tables["locations"]["sync_methods"]