: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(warehouse_sources): support ChartHop API version v2 (#74166)
Tom Owers5f96358459b4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/charthop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/charthop.pyindex 6d551285cbbe..b113372f63c2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/charthop.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/charthop.py@@ -8,7 +8,8 @@ import requestsfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.charthop.settings import (CHARTHOP_ENDPOINTS,- ChartHopEndpointConfig,+ DEFAULT_VERSION,+ resolve_endpoint_version,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (@@ -70,10 +71,10 @@ def _to_charthop_date(value: Any) -> Optional[str]:return min(value, today).isoformat()-def _endpoint_path(config: ChartHopEndpointConfig, org_id: str) -> str:+def _endpoint_path(path_template: str, org_id: str) -> str:# Encode the org id as a single path segment so a crafted value (slashes, query# delimiters) can't redirect the request to a different endpoint with the stored token.- return config.path.format(org_id=quote(org_id, safe=""))+ return path_template.format(org_id=quote(org_id, safe=""))def resolve_org_id(api_key: str, configured_org_id: Optional[str]) -> str:@@ -103,13 +104,19 @@ def resolve_org_id(api_key: str, configured_org_id: Optional[str]) -> str:return orgs[0]["id"]-def check_access(api_key: str, org_id: Optional[str], schema_name: Optional[str]) -> tuple[int, Optional[str]]:+def check_access(+ api_key: str,+ org_id: Optional[str],+ schema_name: Optional[str],+ api_version: str = DEFAULT_VERSION,+) -> tuple[int, Optional[str]]:"""Probe the API to validate credentials.Returns a normalized ``(status, message)``: 200 = reachable, 401 = bad token,403 = valid token without access, 404 = org not found, 0 = network/unexpected error.- Validating a specific schema probes that endpoint with ``limit=1`` so tokens scoped- to a subset of the data fail fast on the schemas they can't read.+ Validating a specific schema probes that endpoint with ``limit=1`` — under the source's+ resolved ``api_version`` so the probe hits the same path a sync would — letting tokens+ scoped to a subset of the data fail fast on the schemas they can't read."""try:resolved_org_id = resolve_org_id(api_key, org_id)@@ -130,7 +137,8 @@ def check_access(api_key: str, org_id: Optional[str], schema_name: Optional[str]return 200, Noneconfig = CHARTHOP_ENDPOINTS[schema_name]- path = _endpoint_path(config, resolved_org_id)+ path_template, _ = resolve_endpoint_version(config, api_version)+ path = _endpoint_path(path_template, resolved_org_id)query = urlencode({"limit": 1, **config.extra_params})_ok, probe_status = validate_via_probe(lambda: make_tracked_session(redact_values=(api_key,)),@@ -152,9 +160,11 @@ def charthop_source(resumable_source_manager: ResumableSourceManager[ChartHopResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,+ api_version: str = DEFAULT_VERSION,) -> SourceResponse:config = CHARTHOP_ENDPOINTS[endpoint]- path = _endpoint_path(config, org_id)+ path_template, incremental_param = resolve_endpoint_version(config, api_version)+ path = _endpoint_path(path_template, org_id)initial_paginator_state: Optional[dict[str, Any]] = Noneresume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None@@ -172,8 +182,8 @@ def charthop_source(params: dict[str, Any] = {"limit": PAGE_SIZE, **config.extra_params}# The ``next`` token is a bare entity id, not a full query, so filters are re-sent on# every page — the date window stays applied across the whole pagination walk.- if config.incremental_param is not None and start_date is not None:- params[config.incremental_param] = start_date+ if incremental_param is not None and start_date is not None:+ params[incremental_param] = start_daterest_config: RESTAPIConfig = {"client": {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/settings.pyindex 6b869c0a2663..f323e0e8f7a4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/settings.py@@ -3,6 +3,24 @@ from typing import Any, Optionalfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# Vendor API versions this source implements, as opaque labels (never parsed or ordered).+# ``v1`` is the legacy pin (the base-class `UNVERSIONED_API_VERSION`); ``v2`` adopts ChartHop's+# v2 ``change`` resource. Only the ``changes`` endpoint's request differs between the two — every+# other resource is served under a single path ChartHop offers, identical for both pins.+CHARTHOP_V1 = "v1"+CHARTHOP_V2 = "v2"+SUPPORTED_VERSIONS = (CHARTHOP_V1, CHARTHOP_V2)+DEFAULT_VERSION = CHARTHOP_V2+++@dataclass+class ChartHopEndpointVersionOverride:+ """Per-version request differences for a resource ChartHop serves under more than one API+ version. Unset fields fall through to the endpoint's base (v1) values."""++ path: Optional[str] = None+ incremental_param: Optional[str] = None+@dataclassclass ChartHopEndpointConfig:@@ -19,6 +37,8 @@ class ChartHopEndpointConfig:partition_key: Optional[str] = None"""A STABLE field to partition on. Never an updated_at-style field, which wouldrewrite partitions on every sync."""+ version_overrides: dict[str, ChartHopEndpointVersionOverride] = field(default_factory=dict)+ """Resolved-``api_version`` → request overrides. Absent versions use the base (v1) request."""# Every ChartHop list endpoint paginates the same way: cursor-by-id via ``from=<last id>``@@ -72,6 +92,15 @@ CHARTHOP_ENDPOINTS: dict[str, ChartHopEndpointConfig] = {"field_type": IncrementalFieldType.Date,},],+ # v2 serves the change list at /v2/org/{orgId}/change and renames the start-date+ # filter param from ``date`` to ``fromDate``; the envelope, cursor, and row fields+ # (including the ``date`` field this partitions/increments on) are unchanged.+ version_overrides={+ CHARTHOP_V2: ChartHopEndpointVersionOverride(+ path="/v2/org/{org_id}/change",+ incremental_param="fromDate",+ ),+ },),"time_off": ChartHopEndpointConfig(name="time_off",@@ -84,3 +113,15 @@ ENDPOINTS = tuple(CHARTHOP_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in CHARTHOP_ENDPOINTS.items()}+++def resolve_endpoint_version(config: ChartHopEndpointConfig, api_version: str) -> tuple[str, Optional[str]]:+ """Effective ``(path template, incremental query param)`` for a resolved ``api_version`` pin.++ A version without an override — including an unknown or legacy label honored verbatim by+ ``resolve_api_version`` — falls back to the base (v1) request rather than being dropped.+ """+ override = config.version_overrides.get(api_version)+ if override is None:+ return config.path, config.incremental_param+ return override.path or config.path, override.incremental_param or config.incremental_paramdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/source.pyindex 724a687e5618..058d59e640e2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/source.py@@ -22,8 +22,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.c)from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.settings import (CHARTHOP_ENDPOINTS,+ DEFAULT_VERSION,ENDPOINTS,INCREMENTAL_FIELDS,+ SUPPORTED_VERSIONS,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (@@ -45,6 +47,8 @@ from products.warehouse_sources.backend.types import ExternalDataSourceTypeclass ChartHopSource(ResumableSource[ChartHopSourceConfig, ChartHopResumeConfig]):lists_tables_without_credentials = True # static endpoint catalog — safe for public docsapi_docs_url = "https://docs.charthop.com/charthop-for-developers"+ supported_versions = SUPPORTED_VERSIONS+ default_version = DEFAULT_VERSION@propertydef source_type(self) -> ExternalDataSourceType:@@ -111,6 +115,9 @@ The organization ID (or slug) is optional — it's detected automatically when yforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:+ # Table set, incremental fields, and primary keys are identical across versions —+ # only the `changes` request path/filter differs (see settings.version_overrides),+ # so discovery doesn't vary by pin.return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)def validate_credentials(@@ -123,7 +130,9 @@ The organization ID (or slug) is optional — it's detected automatically when yif schema_name is not None and schema_name not in CHARTHOP_ENDPOINTS:return False, f"Unknown ChartHop schema '{schema_name}'"- status, message = check_access(config.api_key, config.org_id, schema_name)+ status, message = check_access(+ config.api_key, config.org_id, schema_name, self.resolve_api_version(api_version)+ )if status == 200:return True, None@@ -167,4 +176,5 @@ The organization ID (or slug) is optional — it's detected automatically when ydb_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,+ api_version=self.resolve_api_version(inputs.api_version),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop.pyindex c1c4fc71b001..4ee79d8157bf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop.py@@ -18,7 +18,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.ccharthop_source,resolve_org_id,)-from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.charthop.settings import (+ CHARTHOP_V1,+ CHARTHOP_V2,+ ENDPOINTS,+)# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -161,6 +165,7 @@ class TestPagination:should_use_incremental_field=True,# The saved window must win over the advanced watermark on resume.db_incremental_field_last_value=date(2026, 2, 1),+ api_version=CHARTHOP_V1,))@@ -179,11 +184,38 @@ class TestPagination:_make_manager(),should_use_incremental_field=True,db_incremental_field_last_value=date(2026, 1, 15),+ api_version=CHARTHOP_V1,))assert all(page_params["date"] == "2026-01-15" for page_params in params)+ @parameterized.expand(+ [+ (CHARTHOP_V1, "/v1/org/org-1/change", "date"),+ (CHARTHOP_V2, "/v2/org/org-1/change", "fromDate"),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_changes_endpoint_dispatches_path_and_filter_by_version(+ self, version: str, expected_path: str, expected_param: str, MockSession+ ) -> None:+ session = MockSession.return_value+ params, urls = _wire(session, [_response([])])++ _rows(+ _source(+ "changes",+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 1, 15),+ api_version=version,+ )+ )++ assert urls[0] == f"{CHARTHOP_BASE_URL}{expected_path}"+ assert params[0][expected_param] == "2026-01-15"+@mock.patch(CLIENT_SESSION_PATCH)def test_full_refresh_endpoint_never_sends_date_filter(self, MockSession) -> None:session = MockSession.return_valuediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop_source.pyindex 33d07a6ab67e..4e6b7277e4d6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/charthop/tests/test_charthop_source.py@@ -25,6 +25,11 @@ class TestChartHopSource:def test_source_type(self) -> None:assert self.source.source_type == ExternalDataSourceType.CHARTHOP+ def test_version_declaration_defaults_to_v2(self) -> None:+ # New sources are stamped with default_version; v1 stays supported for existing pins.+ assert self.source.supported_versions == ("v1", "v2")+ assert self.source.default_version == "v2"+def test_org_id_is_a_connection_host_field(self) -> None:# Changing org_id must force the api_key to be re-entered, so the stored token is# never retargeted at another org the editor doesn't hold credentials for.@@ -143,10 +148,16 @@ class TestChartHopSource:assert isinstance(manager, ResumableSourceManager)assert manager._data_class is ChartHopResumeConfig+ @parameterized.expand([("unpinned", None, "v2"), ("legacy", "v1", "v1"), ("v2", "v2", "v2")])@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.charthop.source.resolve_org_id")@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.charthop.source.charthop_source")def test_source_for_pipeline_plumbs_arguments(- self, mock_charthop_source: mock.MagicMock, mock_resolve: mock.MagicMock+ self,+ _name: str,+ pin: str | None,+ expected_version: str,+ mock_charthop_source: mock.MagicMock,+ mock_resolve: mock.MagicMock,) -> None:mock_resolve.return_value = "org-42"inputs = mock.MagicMock()@@ -155,6 +166,7 @@ class TestChartHopSource:inputs.job_id = "job-1"inputs.should_use_incremental_field = Trueinputs.db_incremental_field_last_value = "2026-01-01"+ inputs.api_version = pinmanager = mock.MagicMock()self.source.source_for_pipeline(self.config, manager, inputs)@@ -169,3 +181,14 @@ class TestChartHopSource:assert kwargs["resumable_source_manager"] is managerassert kwargs["should_use_incremental_field"] is Trueassert kwargs["db_incremental_field_last_value"] == "2026-01-01"+ # An unpinned source resolves to default_version so its sync path matches new rows.+ assert kwargs["api_version"] == expected_version++ @parameterized.expand([("unpinned", None, "v2"), ("legacy", "v1", "v1")])+ @mock.patch(CHECK_ACCESS_PATH)+ def test_validate_credentials_probes_under_resolved_version(+ self, _name: str, pin: str | None, expected_version: str, mock_check: mock.MagicMock+ ) -> None:+ mock_check.return_value = (200, None)+ self.source.validate_credentials(self.config, self.team_id, schema_name="changes", api_version=pin)+ assert mock_check.call_args.args == ("charthop-token", None, "changes", expected_version)