: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 Canny API version v2 (#86365)
Tom Owersbc460d834048
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.mdindex 530fca7b5895..45af7814ffce 100644--- a/.agents/skills/warehouse-source-new-version/SKILL.md+++ b/.agents/skills/warehouse-source-new-version/SKILL.md@@ -90,6 +90,7 @@ Add it when any of these hold:- Discovery diffs under the SOURCE pin (`sync_new_schemas`, `refresh_schemas`, bulk sync-defaults). A schema-level `api_version` override on a version whose table set differs from the source's version can be disabled/soft-deleted by that diff — keep overrides to short verification windows, not as a long-term way to hold one table on another version.- When a versioned source sends the pin on any vendor call — discovery _or_ sync (a static endpoint catalog doesn't consume it at discovery, but `get_rows` still sends the version header) — add the vendor's version-rejection error signature (e.g. `406`/`410`) to `get_non_retryable_errors`, otherwise a retired pin turns the retry cadence into a permanent error loop with no user-facing surface.- A version bump can change the auth scheme, not just the wire format. Then the source config needs both credential shapes as optional fields, auth construction dispatches on the resolved version, and `validate_credentials` enforces the pair that version needs — form-level `required` can't express "depends on the pin".+- A version that changes the pagination _mechanism_ (e.g. offset→cursor) 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 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.- A source with no dispatch may currently read its version from a constant on a shared model (e.g. the OAuth `Integration` model) that also drives version-independent flows like OAuth token minting. Repoint only the sync request path onto the resolved pin; leave that constant, since bumping it changes those other flows' version with a blast radius beyond this source.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/canny.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/canny.pyindex 4b9caef1c7b8..0d15e5a4d491 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/canny.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/canny.py@@ -5,7 +5,11 @@ from typing import Any, Optionalimport requestsfrom requests import PreparedRequest, Response-from products.warehouse_sources.backend.temporal.data_imports.sources.canny.settings import CANNY_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.canny.settings import (+ CANNY_API_VERSION_V2,+ CANNY_ENDPOINTS,+ CannyEndpointConfig,+)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 (RESTAPIConfig,@@ -13,7 +17,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import AuthConfigBasefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,OffsetPaginator,+ _inject_param,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -24,11 +30,14 @@ PAGE_SIZE = 100REQUEST_TIMEOUT_SECONDS = 60[email protected](frozen=False)class CannyResumeConfig:- # Offset into the current endpoint's list. Each schema syncs independently, so a single- # skip value is enough to resume — there is no cross-endpoint cursor to track.+ # Offset into the current endpoint's list, for v1 skip/limit pagination. Each schema syncs+ # independently, so a single skip value is enough to resume.skip: int = 0+ # Opaque next-page cursor, for v2 cursor pagination. Only one of `skip`/`cursor` is meaningful+ # per endpoint, chosen by the resolved API version.+ cursor: Optional[str] = Noneclass CannyBodyAuth(AuthConfigBase):@@ -98,21 +107,80 @@ class CannyPaginator(OffsetPaginator):super().update_request(request)+class CannyCursorPaginator(BasePaginator):+ """Canny's v2 cursor pagination: a `cursor` param in the POST body, terminated by `hasNextPage`.++ Mirrors CannyPaginator's 200-with-`{"error": ...}` envelope check so an invalid API key still+ surfaces as an HTTPError the friendly non-retryable mapping can match. `limit` is sent on every+ request; `cursor` is sent only once one is known (a seeded resume cursor, or the previous page's).+ """++ def __init__(self, *, cursor: Optional[str] = None) -> None:+ super().__init__()+ self.limit = PAGE_SIZE+ self._cursor = cursor++ def init_request(self, request: requests.Request) -> None:+ _inject_param(request, "json", "limit", self.limit)+ if self._cursor is not None:+ _inject_param(request, "json", "cursor", self._cursor)++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ try:+ body = response.json()+ except ValueError:+ body = None+ if isinstance(body, dict) and body.get("error"):+ raise requests.HTTPError(f"Canny API error: {body['error']} (url: {response.url})", response=response)++ self._cursor = body.get("cursor") if isinstance(body, dict) else None+ self._has_next_page = bool(isinstance(body, dict) and body.get("hasNextPage"))++ def update_request(self, request: requests.Request) -> None:+ if self._cursor is not None:+ _inject_param(request, "json", "cursor", self._cursor)++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"cursor": self._cursor} if self._has_next_page and self._cursor is not None else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor is not None:+ self._cursor = cursor+ self._has_next_page = True+++def _use_v2_cursor(config: CannyEndpointConfig, api_version: str) -> bool:+ # v2 moves only the endpoints Canny reimplemented behind cursor pagination (those with a+ # `v2_path`); every other endpoint stays on its v1 skip/limit wire even under a v2 pin.+ return api_version == CANNY_API_VERSION_V2 and config.v2_path is not None++def canny_source(api_key: str,endpoint: str,team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[CannyResumeConfig],+ api_version: str,) -> SourceResponse:config = CANNY_ENDPOINTS[endpoint]+ use_cursor = _use_v2_cursor(config, api_version)+ if use_cursor:+ # _use_v2_cursor only returns True when both v2 fields are set.+ assert config.v2_path is not None and config.v2_data_key is not None+ path, data_key = config.v2_path, config.v2_data_key+ else:+ path, data_key = config.path, config.data_keydef extract_records(body: dict[str, Any]) -> list[dict[str, Any]]:# Canny nests the record array under a per-endpoint key; anything else (missing key,# non-list value) is treated as an empty page, matching how the source always behaved.- records = body.get(config.data_key)+ records = body.get(data_key)return records if isinstance(records, list) else []+ paginator: BasePaginator = CannyCursorPaginator() if use_cursor else CannyPaginator(paginated=config.paginated)+rest_config: RESTAPIConfig = {"client": {"base_url": CANNY_BASE_URL,@@ -122,9 +190,9 @@ def canny_source({"name": endpoint,"endpoint": {- "path": config.path,+ "path": path,"method": "post",- "paginator": CannyPaginator(paginated=config.paginated),+ "paginator": paginator,},# The whole body reaches the transform (no data_selector) so the record-array# extraction above can keep the exact legacy empty-page semantics.@@ -137,12 +205,17 @@ def canny_source(if resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()if resume is not None:- initial_paginator_state = {"offset": resume.skip}+ initial_paginator_state = {"cursor": resume.cursor} if use_cursor else {"offset": resume.skip}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields# the last page (the merge dedupes on the primary key) rather than skipping it.- if state and state.get("offset") is not None:+ if not state:+ return+ if use_cursor:+ if state.get("cursor") is not None:+ resumable_source_manager.save_state(CannyResumeConfig(cursor=str(state["cursor"])))+ elif state.get("offset") is not None:resumable_source_manager.save_state(CannyResumeConfig(skip=int(state["offset"])))resource = rest_api_resource(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/settings.pyindex 3934434e8a32..29fe8c155451 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/settings.py@@ -3,18 +3,23 @@ from typing import Optionalfrom products.warehouse_sources.backend.types import IncrementalField-# Canny exposes every resource through a POST `/list` endpoint with skip/limit-# offset pagination and a `hasMore` flag in the body. The secret API key is sent as-# the `apiKey` POST body parameter. There is no server-side updated-since filter on-# any list endpoint, so every stream is full refresh only (see source.py / canny.py).+# Canny exposes every resource through a POST `/list` endpoint. v1 endpoints use skip/limit+# offset pagination with a `hasMore` flag; v2 endpoints (users, companies, comments) use cursor+# pagination with a `cursor` string and a `hasNextPage` flag. The secret API key is sent as the+# `apiKey` POST body parameter for both. There is no server-side updated-since filter on any list+# endpoint, so every stream is full refresh only (see source.py / canny.py).+# Vendor API version labels. v1 is the long-standing wire; v2 is Canny's newer cursor-paginated+# implementation, offered so far only for the endpoints that set `v2_path` below.+CANNY_API_VERSION_V1 = "v1"+CANNY_API_VERSION_V2 = "v2"-@dataclass++@dataclass(frozen=False)class CannyEndpointConfig:- # Path under the API base (https://canny.io/api). Canny still serves every- # resource we sync from its v1 list endpoints.+ # v1 path under the API base (https://canny.io/api), with skip/limit offset pagination.path: str- # Top-level key in the JSON response holding the array of records.+ # Top-level key in the v1 JSON response holding the array of records.data_key: str# Whether the endpoint supports skip/limit pagination. `boards/list` returns# every board in one response with no pagination params or `hasMore` flag.@@ -23,6 +28,14 @@ class CannyEndpointConfig:# because it never changes after a record is created (unlike a `lastSaved` field).partition_key: Optional[str] = "created"primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # v2 cursor-paginated variant, where Canny offers one. When the resolved source pin is v2 and+ # these are set, the endpoint requests the v2 path with cursor pagination; otherwise it stays on+ # the v1 skip/limit path. Both are kept so the table set is identical across versions.+ v2_path: Optional[str] = None+ # Top-level key in the v2 JSON response holding the array of records. Canny keys this per+ # endpoint: `users/list` and `companies/list` keep their named `users`/`companies` keys, while+ # `comments/list` nests records under the generic `items`.+ v2_data_key: Optional[str] = NoneCANNY_ENDPOINTS: dict[str, CannyEndpointConfig] = {@@ -30,12 +43,18 @@ CANNY_ENDPOINTS: dict[str, CannyEndpointConfig] = {"categories": CannyEndpointConfig(path="/v1/categories/list", data_key="categories"),# Changelog entries live under the `entries` list endpoint."changelog_entries": CannyEndpointConfig(path="/v1/entries/list", data_key="entries"),- "comments": CannyEndpointConfig(path="/v1/comments/list", data_key="comments"),- "companies": CannyEndpointConfig(path="/v1/companies/list", data_key="companies"),+ "comments": CannyEndpointConfig(+ path="/v1/comments/list", data_key="comments", v2_path="/v2/comments/list", v2_data_key="items"+ ),+ "companies": CannyEndpointConfig(+ path="/v1/companies/list", data_key="companies", v2_path="/v2/companies/list", v2_data_key="companies"+ ),"posts": CannyEndpointConfig(path="/v1/posts/list", data_key="posts"),"status_changes": CannyEndpointConfig(path="/v1/status_changes/list", data_key="statusChanges"),"tags": CannyEndpointConfig(path="/v1/tags/list", data_key="tags"),- "users": CannyEndpointConfig(path="/v1/users/list", data_key="users"),+ "users": CannyEndpointConfig(+ path="/v1/users/list", data_key="users", v2_path="/v2/users/list", v2_data_key="users"+ ),"votes": CannyEndpointConfig(path="/v1/votes/list", data_key="votes"),}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/source.pyindex 371c998cc0aa..397b6722b2a9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/source.py@@ -15,6 +15,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.canny.cannvalidate_credentials as validate_canny_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.canny.settings import (+ CANNY_API_VERSION_V1,+ CANNY_API_VERSION_V2,CANNY_ENDPOINTS,INCREMENTAL_FIELDS,)@@ -35,8 +37,11 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass CannySource(ResumableSource[CannySourceConfig, CannyResumeConfig]):- supported_versions = ("v1",)- default_version = "v1"+ # Oldest→newest; the default is always the last entry. v2 is Canny's cursor-paginated wire,+ # served today for a subset of endpoints (see settings.py) — new sources default to it while+ # v1-pinned rows keep their skip/limit request path unchanged.+ supported_versions = (CANNY_API_VERSION_V1, CANNY_API_VERSION_V2)+ default_version = CANNY_API_VERSION_V2api_docs_url = "https://developers.canny.io/api-reference"@property@@ -128,4 +133,5 @@ Find your secret API key under **Settings → API** in your Canny dashboard.""",team_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,+ api_version=self.resolve_api_version(inputs.api_version),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/tests/test_canny.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/tests/test_canny.pyindex 277fc63e3203..b12b0fe1d8d2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/tests/test_canny.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/tests/test_canny.py@@ -14,7 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.canny.canncanny_source,validate_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.canny.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.canny.settings import (+ CANNY_API_VERSION_V1,+ CANNY_API_VERSION_V2,+ ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (RESTClientRetryableError,)@@ -73,8 +77,35 @@ def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]-def _source(endpoint: str, manager: mock.MagicMock, api_key: str = "k"):- return canny_source(api_key=api_key, endpoint=endpoint, team_id=1, job_id="j", resumable_source_manager=manager)+def _source(endpoint: str, manager: mock.MagicMock, api_key: str = "k", api_version: str = CANNY_API_VERSION_V1):+ return canny_source(+ api_key=api_key,+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ api_version=api_version,+ )+++def _cursor_page(key: str, ids: list[str], cursor: str | None, has_next: bool) -> Response:+ return _response({key: [{"id": i} for i in ids], "cursor": cursor, "hasNextPage": has_next})+++def _capture(session: mock.MagicMock, responses: list[Response]) -> tuple[list[str], list[dict[str, Any]]]:+ """Like ``_wire`` but also snapshots each request's URL, so v2 path dispatch can be asserted."""+ session.headers = {}+ urls: list[str] = []+ bodies: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ urls.append(request.url)+ bodies.append(dict(request.json or {}))+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return urls, bodiesclass TestCannyBodyAuth:@@ -304,3 +335,81 @@ class TestCannySource:# Every Canny object carries a stable `created` timestamp we partition on.assert response.partition_mode == "datetime"assert response.partition_keys == ["created"]+++class TestV2CursorPagination:+ # Canny's v2 wire is cursor-paginated and keys records per endpoint: users and companies keep+ # their named keys, comments uses the generic `items`.+ V2_ENDPOINTS = [("companies", "companies"), ("comments", "items"), ("users", "users")]++ @pytest.mark.parametrize(("endpoint", "data_key"), V2_ENDPOINTS)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_cursor_paginates_reads_v2_key_and_hits_v2_path(self, MockSession, endpoint: str, data_key: str) -> None:+ session = MockSession.return_value+ urls, bodies = _capture(+ session,+ [+ _cursor_page(data_key, ["a", "b"], cursor="cur-1", has_next=True),+ _cursor_page(data_key, ["c"], cursor=None, has_next=False),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source(endpoint, manager, api_version=CANNY_API_VERSION_V2))++ assert [r["id"] for r in rows] == ["a", "b", "c"]+ assert all(url == f"https://canny.io/api/v2/{endpoint}/list" for url in urls)+ # limit rides every request; the cursor is absent on the first and forwarded on the next.+ assert bodies[0].get("limit") == PAGE_SIZE+ assert "cursor" not in bodies[0]+ assert bodies[1].get("cursor") == "cur-1"+ # The non-terminal page checkpoints its cursor so a crash resumes rather than restarts.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [CannyResumeConfig(cursor="cur-1")]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_seeds_cursor_from_saved_state(self, MockSession) -> None:+ session = MockSession.return_value+ _, bodies = _capture(session, [_cursor_page("companies", ["x"], cursor=None, has_next=False)])++ manager = _make_manager(CannyResumeConfig(cursor="cur-99"))+ rows = _rows(_source("companies", manager, api_version=CANNY_API_VERSION_V2))++ assert bodies[0].get("cursor") == "cur-99"+ assert [r["id"] for r in rows] == ["x"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_error_body_on_v2_raises_http_error(self, MockSession) -> None:+ session = MockSession.return_value+ _capture(session, [_response({"error": "invalid API key"})])++ with pytest.raises(requests.HTTPError, match="invalid API key"):+ _rows(_source("companies", _make_manager(), api_version=CANNY_API_VERSION_V2))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_v2_pin_keeps_non_v2_endpoint_on_v1_skip_wire(self, MockSession) -> None:+ # posts has no v2 implementation, so a v2-pinned source must still request the v1 path with+ # skip/limit pagination — never a guessed /v2/posts/list that would 404.+ session = MockSession.return_value+ urls, bodies = _capture(session, [_page("posts", ["p1"], has_more=False)])++ rows = _rows(_source("posts", _make_manager(), api_version=CANNY_API_VERSION_V2))++ assert urls == ["https://canny.io/api/v1/posts/list"]+ assert bodies[0].get("skip") == 0+ assert bodies[0].get("limit") == PAGE_SIZE+ assert [r["id"] for r in rows] == ["p1"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_v1_pin_keeps_v2_capable_endpoint_on_v1_wire(self, MockSession) -> None:+ # A v1-pinned companies source stays byte-for-byte on the v1 skip/limit path and `companies`+ # key, unaffected by the new default.+ session = MockSession.return_value+ urls, bodies = _capture(session, [_page("companies", ["c1"], has_more=False)])++ rows = _rows(_source("companies", _make_manager(), api_version=CANNY_API_VERSION_V1))++ assert urls == ["https://canny.io/api/v1/companies/list"]+ assert bodies[0].get("skip") == 0+ assert "cursor" not in bodies[0]+ assert [r["id"] for r in rows] == ["c1"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/tests/test_canny_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/tests/test_canny_source.pyindex 2f09890be973..29bb9569f71f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/canny/tests/test_canny_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canny/tests/test_canny_source.py@@ -116,9 +116,25 @@ class TestCannySource:assert isinstance(manager, ResumableSourceManager)assert manager._data_class is CannyResumeConfig+ def test_default_version_is_v2(self) -> None:+ # New sources are created on the newest wire; a NULL pin resolves to it too.+ assert self.source.default_version == "v2"+ assert self.source.supported_versions == ("v1", "v2")+ assert self.source.resolve_api_version(None) == "v2"++ @pytest.mark.parametrize(+ ("pin", "expected_version"),+ [+ (None, "v2"),+ ("v1", "v1"),+ ("v2", "v2"),+ ],+ )@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.canny.source.canny_source")- def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:- inputs = _make_inputs(schema_name="comments", team_id=99, job_id="job-xyz")+ def test_source_for_pipeline_plumbs_resolved_version(+ self, mock_source: mock.MagicMock, pin: str | None, expected_version: str+ ) -> None:+ inputs = _make_inputs(schema_name="comments", team_id=99, job_id="job-xyz", api_version=pin)manager = mock.MagicMock(spec=ResumableSourceManager)self.source.source_for_pipeline(self.config, manager, inputs)@@ -129,6 +145,7 @@ class TestCannySource:team_id=99,job_id="job-xyz",resumable_source_manager=manager,+ api_version=expected_version,)def test_canonical_descriptions_cover_every_endpoint(self) -> None: