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(warehouse_sources): support cdc open data API version v3 (#113232)

Tom Owers4482bdab9204
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index 1b73eccd8d14..2ee0193b469f 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -110,7 +110,7 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP
- A version that drops the sort parameters the old request path used to order rows by the incremental field (for example a fixed newest-first order) breaks the per-batch watermark checkpoint that `sort_mode="asc"` implies. Report `sort_mode="desc"` for those endpoints under the new pin, so the pipeline persists the watermark only when a sync completes, and stop sending the sort params the new version rejects.
- When the new version's list endpoint cannot filter on the table's existing incremental field (it filters only on a different timestamp, or not at all), make those tables full refresh under the new pin by returning version-specific incremental fields from `get_schemas`. Filtering on a substitute timestamp silently skips rows that change or arrive late.
- A partial move that changes the resource's id scheme (internal integer → public UUID) breaks joins between the moved tables and the tables left on the legacy wire, which still carry the old foreign key. Say so in the PR and treat the repin as lossy.
-- A version that changes the pagination _mechanism_ (e.g. offset→cursor, or one opaque cursor param for another, since a token one generation issued means nothing to the other) also changes the resumable checkpoint's persisted shape. Add a new defaulted field to the resume-config dataclass rather than repurposing the existing one — so state persisted under the old version still decodes — and make the seed and save-checkpoint logic dispatch on the resolved version. Reusing one field across incompatible mechanisms corrupts in-flight resumes of the other version. When a table stays on its old wire under the new pin, key the check on the wire that issued the cursor, not on the pin.
+- A version that changes the pagination _mechanism_ (e.g. offset→cursor, or one opaque cursor param for another, since a token one generation issued means nothing to the other) also changes the resumable checkpoint's persisted shape. Add a new defaulted field to the resume-config dataclass rather than repurposing the existing one — so state persisted under the old version still decodes — and make the seed and save-checkpoint logic dispatch on the resolved version. Reusing one field across incompatible mechanisms corrupts in-flight resumes of the other version. When a table stays on its old wire under the new pin, key the check on the wire that issued the cursor, not on the pin. When both mechanisms are positional with a fixed page size (offset↔page number), keep the existing field instead: let the new version's paginator derive its page from the stored offset, so one checkpoint means the same row under either pin.
- Other products can read a synced table's columns by name, e.g. a signal emitter registered on `(source_type, table)` in `products/signals/backend/emission/registry.py`. Grep for the source type outside its directory before a new version renames or nests a column such a reader uses, and keep that column under its old name on the new version's rows.
- When the vendor renames a collection between versions, keep the schema/table name set identical across versions and put the rename in a per-version path on the endpoint config — otherwise discovery diffs orphan the table on repin.
- When the new version has no equivalent for an old endpoint (a dropped collection, not a rename), keep that table only on the versions that serve it and let the table set differ by version — never map it to a guessed path just to keep the sets equal, since docs are the sole source of truth and an unverified path makes a new source surface a table that 404s at sync time.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/cdc_open_data.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/cdc_open_data.py
index 5756bf7a734b..e8e8929ad381 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/cdc_open_data.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/cdc_open_data.py
@@ -3,11 +3,15 @@ from datetime import UTC, date, datetime
from typing import Any, Optional
from urllib.parse import urlencode
+from requests import Request
+
from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import (
CDC_BASE_URL,
PAGE_SIZE,
SOCRATA_ID_FIELD,
SOCRATA_UPDATED_AT_FIELD,
+ SODA2_API_VERSION,
+ SODA3_API_VERSION,
)
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.rest_source import (
@@ -19,7 +23,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
OffsetPaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import AuthConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ AuthConfig,
+ Endpoint,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -48,19 +55,29 @@ def _auth_config(app_token: str) -> Optional[AuthConfig]:
return {"type": "api_key", "api_key": app_token, "name": APP_TOKEN_HEADER, "location": "header"}
-def _probe_url(dataset_id: str) -> str:
- return f"{CDC_BASE_URL}/resource/{dataset_id}.json?{urlencode({'$limit': 1})}"
+class _Soda3Paginator(OffsetPaginator):
+ """Sends SODA 3's 1-indexed `page` body field, but keeps a row offset as its state so a saved
+ `CdcOpenDataResumeConfig.next_offset` means the same row under either API version."""
+ def init_request(self, request: Request) -> None:
+ self.update_request(request)
-def cdc_open_data_source(
- dataset_id: str,
- app_token: str,
- team_id: int,
- job_id: str,
- resumable_source_manager: ResumableSourceManager[CdcOpenDataResumeConfig],
- should_use_incremental_field: bool,
- db_incremental_field_last_value: Optional[Any],
-) -> SourceResponse:
+ def update_request(self, request: Request) -> None:
+ if request.json is None:
+ request.json = {}
+ request.json["page"] = {"pageNumber": self.offset // self.limit + 1, "pageSize": self.limit}
+
+
+def _probe_url(dataset_id: str, api_version: str) -> str:
+ if api_version == SODA3_API_VERSION:
+ query = urlencode({"query": "SELECT *", "pageNumber": 1, "pageSize": 1})
+ return f"{CDC_BASE_URL}/api/v3/views/{dataset_id}/query.json?{query}"
+ if api_version == SODA2_API_VERSION:
+ return f"{CDC_BASE_URL}/resource/{dataset_id}.json?{urlencode({'$limit': 1})}"
+ raise ValueError(f"Unsupported CDC Open Data API version: {api_version}")
+
+
+def _soda2_endpoint(dataset_id: str, should_use_incremental_field: bool, where_value: Optional[str]) -> Endpoint:
params: dict[str, Any] = {
# Every dataset's own columns vary, but every dataset carries these Socrata system
# fields; requesting them explicitly (rather than relying on a version-specific
@@ -70,17 +87,66 @@ def cdc_open_data_source(
if should_use_incremental_field
else SOCRATA_ID_FIELD,
}
- if should_use_incremental_field and db_incremental_field_last_value is not None:
- formatted_value = _format_where_value(db_incremental_field_last_value)
- params["$where"] = f"{SOCRATA_UPDATED_AT_FIELD} > '{formatted_value}'"
-
- paginator = OffsetPaginator(
- limit=PAGE_SIZE,
- offset_param="$offset",
- limit_param="$limit",
- total_path=None,
+ if where_value is not None:
+ params["$where"] = f"{SOCRATA_UPDATED_AT_FIELD} > '{where_value}'"
+ return {
+ "path": f"/resource/{dataset_id}.json",
+ "params": params,
+ # A dataset endpoint always returns a bare JSON array; a non-list body means a
+ # transient/error payload rather than zero rows.
+ "data_selector_required": True,
+ }
+
+
+def _soda3_endpoint(dataset_id: str, should_use_incremental_field: bool, where_value: Optional[str]) -> Endpoint:
+ query = "SELECT *"
+ if where_value is not None:
+ query += f" WHERE {SOCRATA_UPDATED_AT_FIELD} > '{where_value}'"
+ query += (
+ f" ORDER BY {SOCRATA_UPDATED_AT_FIELD}, {SOCRATA_ID_FIELD}"
+ if should_use_incremental_field
+ else f" ORDER BY {SOCRATA_ID_FIELD}"
+ )
+ return {
+ "path": f"/api/v3/views/{dataset_id}/query.json",
+ "method": "POST",
+ "json": {"query": query, "includeSystem": True},
+ "data_selector_required": True,
+ }
+
+
+def cdc_open_data_source(
+ dataset_id: str,
+ app_token: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CdcOpenDataResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+ api_version: str,
+) -> SourceResponse:
+ where_value = (
+ _format_where_value(db_incremental_field_last_value)
+ if should_use_incremental_field and db_incremental_field_last_value is not None
+ else None
)
+ endpoint: Endpoint
+ paginator: OffsetPaginator
+ if api_version == SODA3_API_VERSION:
+ endpoint = _soda3_endpoint(dataset_id, should_use_incremental_field, where_value)
+ paginator = _Soda3Paginator(limit=PAGE_SIZE, total_path=None)
+ elif api_version == SODA2_API_VERSION:
+ endpoint = _soda2_endpoint(dataset_id, should_use_incremental_field, where_value)
+ paginator = OffsetPaginator(
+ limit=PAGE_SIZE,
+ offset_param="$offset",
+ limit_param="$limit",
+ total_path=None,
+ )
+ else:
+ raise ValueError(f"Unsupported CDC Open Data API version: {api_version}")
+
initial_paginator_state: Optional[dict[str, Any]] = None
if resumable_source_manager.can_resume():
resume_config = resumable_source_manager.load_state()
@@ -105,13 +171,7 @@ def cdc_open_data_source(
"write_disposition": {"disposition": "merge", "strategy": "upsert"}
if should_use_incremental_field
else "replace",
- "endpoint": {
- "path": f"/resource/{dataset_id}.json",
- "params": params,
- # A dataset endpoint always returns a bare JSON array; a non-list body means a
- # transient/error payload rather than zero rows.
- "data_selector_required": True,
- },
+ "endpoint": endpoint,
"table_format": "delta",
}
config: RESTAPIConfig = {
@@ -137,13 +197,16 @@ def cdc_open_data_source(
)
-def validate_cdc_open_data_credentials(app_token: str, dataset_id: str) -> tuple[bool, str | None]:
- """Probe one dataset's resource endpoint to confirm it exists and the app token (if any) is valid."""
+def validate_cdc_open_data_credentials(app_token: str, dataset_id: str, api_version: str) -> tuple[bool, str | None]:
+ """Probe one dataset's query endpoint to confirm it exists and the app token (if any) is valid."""
+ if api_version == SODA3_API_VERSION and not app_token:
+ return False, "Enter a Socrata app token. The current data.cdc.gov API requires one to read datasets."
headers = {APP_TOKEN_HEADER: app_token} if app_token else None
ok, status = validate_via_probe(
lambda: make_tracked_session(redact_values=(app_token,) if app_token else ()),
- _probe_url(dataset_id),
+ _probe_url(dataset_id, api_version),
headers=headers,
+ allow_redirects=False,
)
if ok:
return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/settings.py
index 9dae436169c6..cb691daa9c62 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/settings.py
@@ -7,11 +7,17 @@ the user configures, not a vendor-defined catalog.
import re
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
CDC_BASE_URL = "https://data.cdc.gov"
+# The legacy label reads the SODA 2.x `/resource/{id}.json` endpoint; "v3" reads SODA 3.0's
+# `/api/v3/views/{id}/query.json`, which takes a POSTed SoQL query and requires an app token.
+SODA2_API_VERSION = UNVERSIONED_API_VERSION
+SODA3_API_VERSION = "v3"
+
# Socrata assigns every dataset a "4x4" identifier: two 4-character alphanumeric groups joined
# by a hyphen (e.g. "9bhg-hcku"), visible in the dataset's data.cdc.gov URL.
DATASET_ID_PATTERN = re.compile(r"^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/source.py
index d4d1eab02b77..67022b4a86f8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/source.py
@@ -17,6 +17,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_d
INCREMENTAL_FIELDS,
MAX_DATASET_IDS,
SOCRATA_ID_FIELD,
+ SODA2_API_VERSION,
+ SODA3_API_VERSION,
parse_dataset_ids,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
@@ -33,6 +35,8 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class CdcOpenDataSource(ResumableSource[CdcOpenDataSourceConfig, CdcOpenDataResumeConfig]):
api_docs_url = "https://dev.socrata.com/consumers/getting-started.html"
+ supported_versions = (SODA2_API_VERSION, SODA3_API_VERSION)
+ default_version = SODA3_API_VERSION
@property
def source_type(self) -> ExternalDataSourceType:
@@ -40,6 +44,8 @@ class CdcOpenDataSource(ResumableSource[CdcOpenDataSourceConfig, CdcOpenDataResu
def get_non_retryable_errors(self) -> dict[str, str | None]:
return {
+ # Matched first: SODA 3 rejects a missing token too, so "remove it" is not a fix there.
+ "403 Client Error: Forbidden for url: https://data.cdc.gov/api/v3/": "Invalid or missing CDC Open Data app token. Check the token in the source settings.",
"403 Client Error: Forbidden for url: https://data.cdc.gov": "Invalid CDC Open Data app token. Check the token in the source settings, or remove it to use the shared public pool.",
"404 Client Error: Not Found for url: https://data.cdc.gov": "Dataset not found on data.cdc.gov. Check the dataset ID in the source settings.",
}
@@ -99,7 +105,9 @@ class CdcOpenDataSource(ResumableSource[CdcOpenDataSourceConfig, CdcOpenDataResu
)
probe_dataset_id = schema_name if schema_name in dataset_ids else dataset_ids[0]
- return validate_cdc_open_data_credentials(config.app_token or "", probe_dataset_id)
+ return validate_cdc_open_data_credentials(
+ config.app_token or "", probe_dataset_id, self.resolve_api_version(api_version)
+ )
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CdcOpenDataResumeConfig]:
return ResumableSourceManager[CdcOpenDataResumeConfig](inputs, CdcOpenDataResumeConfig)
@@ -120,6 +128,7 @@ class CdcOpenDataSource(ResumableSource[CdcOpenDataSourceConfig, CdcOpenDataResu
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
else None,
+ api_version=self.resolve_api_version(inputs.api_version),
)
@property
@@ -134,7 +143,7 @@ class CdcOpenDataSource(ResumableSource[CdcOpenDataSourceConfig, CdcOpenDataResu
Find a dataset's ID in its data.cdc.gov URL — for example `9bhg-hcku` in `https://data.cdc.gov/d/9bhg-hcku`. Browse the full catalog at [data.cdc.gov](https://data.cdc.gov).
-No account is required. Optionally, register a free [Socrata app token](https://support.socrata.com/hc/en-us/articles/210138558-Generating-an-App-Token) to avoid the shared public rate limit.
+You need a free [Socrata app token](https://support.socrata.com/hc/en-us/articles/210138558-Generating-an-App-Token) to connect. The current data.cdc.gov API requires one.
""",
docsUrl="https://posthog.com/docs/cdp/sources/cdc-open-data",
iconPath="/static/services/cdc_open_data.png",
@@ -152,12 +161,12 @@ No account is required. Optionally, register a free [Socrata app token](https://
),
SourceFieldInputConfig(
name="app_token",
- label="App token (optional)",
+ label="App token",
type=SourceFieldInputConfigType.PASSWORD,
required=False,
placeholder="",
secret=True,
- caption="Lifts the shared per-IP rate limit. Leave blank to use the public pool.",
+ caption="Required for new sources. Register a free token in your Socrata profile.",
),
],
),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data.py
index 76bda4e99eee..03192a3d5abf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data.py
@@ -1,8 +1,10 @@
+import copy
import json
-from collections.abc import Iterable
+from collections.abc import Callable, Iterable
from datetime import UTC, date, datetime, timedelta
from typing import Any, cast
+import pytest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -12,10 +14,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_d
CdcOpenDataResumeConfig,
_auth_config,
_format_where_value,
+ _probe_url,
cdc_open_data_source,
validate_cdc_open_data_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import PAGE_SIZE
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import (
+ PAGE_SIZE,
+ SODA2_API_VERSION,
+ SODA3_API_VERSION,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -42,6 +49,30 @@ class TestAuthConfig:
assert auth == {"type": "api_key", "api_key": "my-token", "name": "X-App-Token", "location": "header"}
+class TestProbeUrl:
+ @parameterized.expand(
+ [
+ (SODA2_API_VERSION, "https://data.cdc.gov/resource/9bhg-hcku.json?%24limit=1"),
+ (
+ SODA3_API_VERSION,
+ "https://data.cdc.gov/api/v3/views/9bhg-hcku/query.json?query=SELECT+%2A&pageNumber=1&pageSize=1",
+ ),
+ ]
+ )
+ def test_probe_url_reads_one_row_from_the_versioned_endpoint(self, api_version: str, expected: str) -> None:
+ assert _probe_url("9bhg-hcku", api_version) == expected
+
+ def test_unknown_version_raises_instead_of_falling_back(self) -> None:
+ with pytest.raises(ValueError):
+ _probe_url("9bhg-hcku", "v2")
+
+
+_SENT_POSITION: dict[str, Callable[[dict[str, Any]], int]] = {
+ SODA2_API_VERSION: lambda request: request["params"]["$offset"],
+ SODA3_API_VERSION: lambda request: request["json"]["page"]["pageNumber"],
+}
+
+
def _make_http_response(body: Any, status_code: int = 200) -> Response:
resp = Response()
resp.status_code = status_code
@@ -85,20 +116,30 @@ class TestValidateCdcOpenDataCredentials:
"products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data.validate_via_probe",
return_value=(probe_status == 200, probe_status),
):
- assert validate_cdc_open_data_credentials("some-token", "aaaa-aaaa") == expected
+ assert validate_cdc_open_data_credentials("some-token", "aaaa-aaaa", SODA2_API_VERSION) == expected
def test_redacts_app_token_from_captured_samples(self) -> None:
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data.validate_via_probe",
return_value=(True, 200),
) as mock_probe:
- validate_cdc_open_data_credentials("super-secret-token", "9bhg-hcku")
+ validate_cdc_open_data_credentials("super-secret-token", "9bhg-hcku", SODA3_API_VERSION)
session_factory = mock_probe.call_args.args[0]
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data.make_tracked_session"
) as mock_make_session:
session_factory()
mock_make_session.assert_called_once_with(redact_values=("super-secret-token",))
+ assert mock_probe.call_args.kwargs["allow_redirects"] is False
+
+ def test_soda3_rejects_missing_app_token_without_probing(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.cdc_open_data.validate_via_probe",
+ ) as mock_probe:
+ valid, message = validate_cdc_open_data_credentials("", "9bhg-hcku", SODA3_API_VERSION)
+ assert valid is False
+ assert message is not None and "app token" in message
+ mock_probe.assert_not_called()
class TestCdcOpenDataSourceResumeBehavior:
@@ -110,12 +151,20 @@ class TestCdcOpenDataSourceResumeBehavior:
responses: list[Response],
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Any = None,
+ api_version: str = SODA2_API_VERSION,
) -> tuple[MagicMock, list[dict[str, Any]]]:
- sent_params: list[dict[str, Any]] = []
+ sent_requests: list[dict[str, Any]] = []
response_iter = iter(responses)
def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
- sent_params.append(dict(request.params or {}))
+ sent_requests.append(
+ {
+ "method": request.method,
+ "url": request.url,
+ "params": dict(request.params or {}),
+ "json": copy.deepcopy(request.json),
+ }
+ )
return next(response_iter)
with patch(
@@ -134,35 +183,73 @@ class TestCdcOpenDataSourceResumeBehavior:
resumable_source_manager=manager,
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
+ api_version=api_version,
)
list(cast(Iterable[Any], source_response.items()))
- return mock_session, sent_params
+ return mock_session, sent_requests
def test_full_refresh_orders_by_id_with_no_where_filter(self) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
responses = [_make_http_response([{":id": "row-1"}])]
- _, sent_params = self._drive(manager, responses)
+ _, sent = self._drive(manager, responses)
- assert sent_params[0]["$order"] == ":id"
- assert "$where" not in sent_params[0]
- assert sent_params[0]["$$exclude_system_fields"] == "false"
+ assert sent[0]["url"].endswith("/resource/9bhg-hcku.json")
+ assert sent[0]["params"]["$order"] == ":id"
+ assert "$where" not in sent[0]["params"]
+ assert sent[0]["params"]["$$exclude_system_fields"] == "false"
def test_incremental_sync_adds_where_filter_and_orders_by_updated_at(self) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
responses = [_make_http_response([{":id": "row-1", ":updated_at": "2024-06-02T00:00:00.000"}])]
- _, sent_params = self._drive(
+ _, sent = self._drive(
manager,
responses,
should_use_incremental_field=True,
db_incremental_field_last_value=datetime(2024, 6, 1, 0, 0, 0),
)
- assert sent_params[0]["$order"] == ":updated_at,:id"
- assert sent_params[0]["$where"] == ":updated_at > '2024-06-01T00:00:00'"
+ assert sent[0]["params"]["$order"] == ":updated_at,:id"
+ assert sent[0]["params"]["$where"] == ":updated_at > '2024-06-01T00:00:00'"
+
+ @parameterized.expand(
+ [
+ ("full_refresh", False, None, "SELECT * ORDER BY :id"),
+ ("incremental_first_sync", True, None, "SELECT * ORDER BY :updated_at, :id"),
+ (
+ "incremental_with_watermark",
+ True,
+ datetime(2024, 6, 1, 0, 0, 0),
+ "SELECT * WHERE :updated_at > '2024-06-01T00:00:00' ORDER BY :updated_at, :id",
+ ),
+ ]
+ )
+ def test_soda3_posts_soql_query_to_views_endpoint(
+ self, _name: str, should_use_incremental_field: bool, last_value: Any, expected_query: str
+ ) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{":id": "row-1"}])]
+ _, sent = self._drive(
+ manager,
+ responses,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ api_version=SODA3_API_VERSION,
+ )
+
+ assert sent[0]["method"].upper() == "POST"
+ assert sent[0]["url"].endswith("/api/v3/views/9bhg-hcku/query.json")
+ assert sent[0]["params"] == {}
+ assert sent[0]["json"] == {
+ "query": expected_query,
+ "includeSystem": True,
+ "page": {"pageNumber": 1, "pageSize": PAGE_SIZE},
+ }
def test_incremental_sync_without_last_value_omits_where_filter(self) -> None:
# First-ever incremental sync has no watermark yet, so it must not filter anything out.
@@ -170,11 +257,19 @@ class TestCdcOpenDataSourceResumeBehavior:
manager.can_resume.return_value = False
responses = [_make_http_response([{":id": "row-1"}])]
- _, sent_params = self._drive(manager, responses, should_use_incremental_field=True)
+ _, sent = self._drive(manager, responses, should_use_incremental_field=True)
- assert "$where" not in sent_params[0]
+ assert "$where" not in sent[0]["params"]
- def test_fresh_run_saves_offset_after_each_non_terminal_page(self) -> None:
+ @parameterized.expand(
+ [
+ (SODA2_API_VERSION, [0, PAGE_SIZE]),
+ (SODA3_API_VERSION, [1, 2]),
+ ]
+ )
+ def test_fresh_run_saves_offset_after_each_non_terminal_page(
+ self, api_version: str, expected_sent: list[int]
+ ) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = False
@@ -183,23 +278,28 @@ class TestCdcOpenDataSourceResumeBehavior:
_make_http_response(full_page),
_make_http_response([{":id": "row-last"}]),
]
- _, sent_params = self._drive(manager, responses)
+ _, sent = self._drive(manager, responses, api_version=api_version)
- offsets_sent = [p.get("$offset") for p in sent_params]
- assert offsets_sent == [0, PAGE_SIZE]
+ assert [_SENT_POSITION[api_version](request) for request in sent] == expected_sent
saved = [call.args[0] for call in manager.save_state.call_args_list]
assert saved == [CdcOpenDataResumeConfig(next_offset=PAGE_SIZE)]
- def test_resume_seeds_paginator_with_saved_offset(self) -> None:
+ @parameterized.expand(
+ [
+ (SODA2_API_VERSION, 40_000),
+ (SODA3_API_VERSION, 40_000 // PAGE_SIZE + 1),
+ ]
+ )
+ def test_resume_seeds_paginator_with_saved_offset(self, api_version: str, expected_sent: int) -> None:
manager = MagicMock(spec=ResumableSourceManager)
manager.can_resume.return_value = True
manager.load_state.return_value = CdcOpenDataResumeConfig(next_offset=40_000)
responses = [_make_http_response([{":id": "row-1"}])]
- _, sent_params = self._drive(manager, responses)
+ _, sent = self._drive(manager, responses, api_version=api_version)
- assert sent_params[0]["$offset"] == 40_000
+ assert _SENT_POSITION[api_version](sent[0]) == expected_sent
manager.load_state.assert_called_once()
def test_does_not_load_state_when_cannot_resume(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data_source.py
index c6ffe2222e3a..9fe42ef8ca5f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cdc_open_data/tests/test_cdc_open_data_source.py
@@ -3,7 +3,11 @@ from unittest import mock
from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data import source as source_module
-from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import MAX_DATASET_IDS
+from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.settings import (
+ MAX_DATASET_IDS,
+ SODA2_API_VERSION,
+ SODA3_API_VERSION,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.cdc_open_data.source import CdcOpenDataSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cdcopendata import (
CdcOpenDataSourceConfig,
@@ -32,12 +36,38 @@ class TestCdcOpenDataSource:
@parameterized.expand(
[
- ("forbidden", "403 Client Error: Forbidden for url: https://data.cdc.gov/resource/x.json?%24limit=1"),
- ("not_found", "404 Client Error: Not Found for url: https://data.cdc.gov/resource/x.json?%24limit=1"),
+ (
+ "soda2_forbidden",
+ "403 Client Error: Forbidden for url: https://data.cdc.gov/resource/x.json?%24limit=1",
+ "remove it",
+ ),
+ (
+ "soda2_not_found",
+ "404 Client Error: Not Found for url: https://data.cdc.gov/resource/x.json?%24limit=1",
+ None,
+ ),
+ (
+ "soda3_forbidden",
+ "403 Client Error: Forbidden for url: https://data.cdc.gov/api/v3/views/x/query.json",
+ "Invalid or missing",
+ ),
+ (
+ "soda3_not_found",
+ "404 Client Error: Not Found for url: https://data.cdc.gov/api/v3/views/x/query.json",
+ None,
+ ),
]
)
- def test_non_retryable_errors_cover_bad_token_and_missing_dataset(self, _name: str, observed: str) -> None:
- assert any(key in observed for key in self.source.get_non_retryable_errors())
+ def test_non_retryable_errors_cover_bad_token_and_missing_dataset(
+ self, _name: str, observed: str, expected_in_message: str | None
+ ) -> None:
+ # The first matching pattern wins when the error is surfaced, so check that one.
+ message = next(
+ (msg for key, msg in self.source.get_non_retryable_errors().items() if key in observed), "<no match>"
+ )
+ assert message != "<no match>"
+ if expected_in_message is not None:
+ assert message is not None and expected_in_message in message
def test_validate_credentials_requires_at_least_one_dataset_id(self) -> None:
config = CdcOpenDataSourceConfig(dataset_ids=" ", app_token=None)
@@ -64,28 +94,53 @@ class TestCdcOpenDataSource:
assert message is not None and str(MAX_DATASET_IDS) in message
mock_validate.assert_not_called()
+ @parameterized.expand(
+ [
+ ("new_source_uses_default", None, SODA3_API_VERSION),
+ ("pinned_legacy_source", SODA2_API_VERSION, SODA2_API_VERSION),
+ ("pinned_soda3_source", SODA3_API_VERSION, SODA3_API_VERSION),
+ ]
+ )
+ def test_validate_credentials_probes_first_dataset_at_source_create(
+ self, _name: str, api_version: str | None, expected_version: str
+ ) -> None:
+ with mock.patch.object(
+ source_module, "validate_cdc_open_data_credentials", return_value=(True, None)
+ ) as mock_validate:
+ valid, message = self.source.validate_credentials(
+ self.config, team_id=1, schema_name=None, api_version=api_version
+ )
+ assert (valid, message) == (True, None)
+ mock_validate.assert_called_once_with("", "9bhg-hcku", expected_version)
+
def test_validate_credentials_probes_the_requested_schema(self) -> None:
with mock.patch.object(
source_module, "validate_cdc_open_data_credentials", return_value=(True, None)
) as mock_validate:
self.source.validate_credentials(self.config, team_id=1, schema_name="vbim-akqf")
- mock_validate.assert_called_once_with("", "vbim-akqf")
+ mock_validate.assert_called_once_with("", "vbim-akqf", SODA3_API_VERSION)
def test_validate_credentials_falls_back_to_first_dataset_for_unknown_schema_name(self) -> None:
with mock.patch.object(
source_module, "validate_cdc_open_data_credentials", return_value=(True, None)
) as mock_validate:
self.source.validate_credentials(self.config, team_id=1, schema_name="not-configured")
- mock_validate.assert_called_once_with("", "9bhg-hcku")
+ mock_validate.assert_called_once_with("", "9bhg-hcku", SODA3_API_VERSION)
@parameterized.expand(
[
- ("incremental_sync_passes_last_value", True, "2024-01-01", "2024-01-01"),
- ("full_refresh_omits_last_value", False, "2024-01-01", None),
+ ("incremental_sync_passes_last_value", True, "2024-01-01", "2024-01-01", SODA2_API_VERSION),
+ ("full_refresh_omits_last_value", False, "2024-01-01", None, SODA2_API_VERSION),
+ ("soda3_pin_reaches_request_layer", True, "2024-01-01", "2024-01-01", SODA3_API_VERSION),
]
)
def test_source_for_pipeline_passes_expected_kwargs(
- self, _name: str, should_use_incremental_field: bool, last_value: str, expected_last_value: str | None
+ self,
+ _name: str,
+ should_use_incremental_field: bool,
+ last_value: str,
+ expected_last_value: str | None,
+ api_version: str,
) -> None:
inputs = mock.MagicMock()
inputs.schema_name = "9bhg-hcku"
@@ -93,6 +148,7 @@ class TestCdcOpenDataSource:
inputs.job_id = "job-1"
inputs.should_use_incremental_field = should_use_incremental_field
inputs.db_incremental_field_last_value = last_value
+ inputs.api_version = api_version
manager = mock.MagicMock()
with mock.patch.object(source_module, "cdc_open_data_source") as mock_source:
@@ -107,3 +163,4 @@ class TestCdcOpenDataSource:
assert kwargs["resumable_source_manager"] is manager
assert kwargs["should_use_incremental_field"] == should_use_incremental_field
assert kwargs["db_incremental_field_last_value"] == expected_last_value
+ assert kwargs["api_version"] == api_version