:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement canny import source (#65622)
Tom Owers3f3671b6cf72
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 12e3c4d99317..00e6df0749e9 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -68,6 +68,7 @@ the row lists both.| buildkite | HTTP | requests | ✅ || calendly | HTTP | requests | ✅ || campaign_monitor | HTTP | requests | ✅ |+| canny | HTTP | requests | ✅ || chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ || checkout_com | HTTP | requests | ✅ || coda | HTTP | requests | ✅ |@@ -309,7 +310,6 @@ doesn't conflict with concurrent PRs.- callrail- campaign_manager_360- campayn-- canny- capsule_crm- captain_data- care_quality_commissiondiff --git a/posthog/temporal/data_imports/sources/canny/canny.py b/posthog/temporal/data_imports/sources/canny/canny.pynew file mode 100644index 000000000000..af45591977a4--- /dev/null+++ b/posthog/temporal/data_imports/sources/canny/canny.py@@ -0,0 +1,161 @@+import dataclasses+from collections.abc import Iterator+from typing import Any++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.canny.settings import CANNY_ENDPOINTS, CannyEndpointConfig+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++CANNY_BASE_URL = "https://canny.io/api"+# Airbyte's community connector pages every Canny list endpoint at 100 records.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class CannyRetryableError(Exception):+ """Raised on 429/5xx so tenacity retries; never reaches get_non_retryable_errors."""+++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.+ skip: int = 0+++def _build_body(api_key: str, config: CannyEndpointConfig, skip: int) -> dict[str, Any]:+ body: dict[str, Any] = {"apiKey": api_key}+ if config.paginated:+ body["skip"] = skip+ body["limit"] = PAGE_SIZE+ return body+++def _handle_response(response: requests.Response, url: str, logger: FilteringBoundLogger) -> dict[str, Any]:+ """Classify a single Canny response: retryable, terminal failure, or success body."""+ if response.status_code == 429 or response.status_code >= 500:+ raise CannyRetryableError(f"Canny API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Canny API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Canny returns 200 with an `{"error": "..."}` body for some failures (e.g. an invalid+ # API key). Surface it as an HTTPError so the friendly non-retryable mapping can match it.+ if isinstance(data, dict) and data.get("error"):+ raise requests.HTTPError(f"Canny API error: {data['error']} (url: {url})", response=response)++ return data+++@retry(+ retry=retry_if_exception_type((CannyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ body: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ # Canny authenticates via the `apiKey` POST body parameter, so every list request is a+ # form-encoded POST rather than a GET.+ response = session.post(url, data=body, timeout=REQUEST_TIMEOUT_SECONDS)+ return _handle_response(response, url, logger)+++def _extract_records(data: dict[str, Any], config: CannyEndpointConfig) -> list[dict[str, Any]]:+ records = data.get(config.data_key)+ if isinstance(records, list):+ return records+ return []+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CannyResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = CANNY_ENDPOINTS[endpoint]+ url = f"{CANNY_BASE_URL}{config.path}"+ # Redact the secret so it never lands in tracked HTTP logs/samples — it travels in the POST body.+ session = make_tracked_session(redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ skip = resume.skip if resume is not None else 0+ if resume is not None:+ logger.debug(f"Canny: resuming endpoint={endpoint} from skip={skip}")++ while True:+ data = _fetch_page(session, url, _build_body(api_key, config, skip), logger)+ records = _extract_records(data, config)++ if records:+ yield records++ if not config.paginated or not data.get("hasMore"):+ break++ # Advance, then persist — saving AFTER yielding means a crash re-yields the last page+ # (the merge dedupes on the primary key) rather than skipping it.+ skip += PAGE_SIZE+ if records:+ resumable_source_manager.save_state(CannyResumeConfig(skip=skip))+++def canny_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CannyResumeConfig],+) -> SourceResponse:+ config = CANNY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ 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,+ )+++def validate_credentials(api_key: str) -> bool:+ # boards/list is the cheapest probe: no pagination, returns quickly, and requires only a+ # valid API key (every workspace has at least one board). Reuse the catalog path so this can+ # never drift from the synced endpoint.+ url = f"{CANNY_BASE_URL}{CANNY_ENDPOINTS['boards'].path}"+ try:+ response = make_tracked_session(redact_values=(api_key,)).post(+ url, data={"apiKey": api_key}, timeout=REQUEST_TIMEOUT_SECONDS+ )+ except Exception:+ return False++ if not response.ok:+ return False++ try:+ body = response.json()+ except ValueError:+ return False++ return not (isinstance(body, dict) and body.get("error"))diff --git a/posthog/temporal/data_imports/sources/canny/canonical_descriptions.py b/posthog/temporal/data_imports/sources/canny/canonical_descriptions.pynew file mode 100644index 000000000000..314bc3e32091--- /dev/null+++ b/posthog/temporal/data_imports/sources/canny/canonical_descriptions.py@@ -0,0 +1,160 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Descriptions are taken from Canny's official API reference (https://developers.canny.io/api-reference).+# Keys match the endpoint names returned by `get_schemas` / declared in settings.py.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "boards": {+ "description": "A board is a collection of posts (feature requests, bugs, ideas) shown to your users.",+ "docs_url": "https://developers.canny.io/api-reference#boards",+ "columns": {+ "id": "A unique identifier for the board.",+ "created": "Time at which the board was created, in ISO 8601 format.",+ "name": "The board's name.",+ "postCount": "The number of non-deleted posts associated with the board.",+ "url": "The URL to the board's page.",+ "isPrivate": "Whether the board is set to private in the admin settings.",+ "privateComments": "Whether comments on this board are private to admins.",+ "token": "The board's unique token, used by the widget.",+ },+ },+ "categories": {+ "description": "A category groups posts within a board.",+ "docs_url": "https://developers.canny.io/api-reference#categories",+ "columns": {+ "id": "A unique identifier for the category.",+ "board": "The board this category belongs to.",+ "created": "Time at which the category was created, in ISO 8601 format.",+ "name": "The name of the category.",+ "parentID": "The id of the parent category, if this is a subcategory.",+ "postCount": "The number of posts in this category.",+ "url": "The URL to the category's page.",+ },+ },+ "changelog_entries": {+ "description": "A changelog entry announcing product updates to your users.",+ "docs_url": "https://developers.canny.io/api-reference#changelog",+ "columns": {+ "id": "A unique identifier for the entry.",+ "created": "Time at which the entry was created, in ISO 8601 format.",+ "lastSaved": "Time at which the entry was last edited, in ISO 8601 format.",+ "publishedAt": "Time at which the entry was published, in ISO 8601 format.",+ "scheduledFor": "Time the entry is scheduled to publish, in ISO 8601 format.",+ "labels": "The labels applied to the entry.",+ "markdownDetails": "The entry's body content, in Markdown.",+ "plaintextDetails": "The entry's body content, as plain text.",+ "posts": "The posts linked to this changelog entry.",+ "status": "The publication status of the entry (e.g. draft, published).",+ "title": "The title of the entry.",+ "types": "The types/tags of the entry (e.g. new, improved, fixed).",+ "url": "The URL to the entry's page.",+ },+ },+ "comments": {+ "description": "A comment left by a user or admin on a post.",+ "docs_url": "https://developers.canny.io/api-reference#comments",+ "columns": {+ "id": "A unique identifier for the comment.",+ "author": "The user who authored the comment.",+ "board": "The board the comment's post belongs to.",+ "created": "Time at which the comment was created, in ISO 8601 format.",+ "imageURLs": "Image URLs attached to the comment.",+ "internal": "Whether the comment is an internal (admin-only) comment.",+ "likeCount": "The number of likes the comment has received.",+ "mentions": "Users mentioned in the comment.",+ "parentID": "The id of the parent comment, if this is a reply.",+ "post": "The post the comment was left on.",+ "private": "Whether the comment is private.",+ "value": "The text content of the comment.",+ },+ },+ "companies": {+ "description": "A company that your users belong to, used to segment feedback.",+ "docs_url": "https://developers.canny.io/api-reference#companies",+ "columns": {+ "id": "A unique identifier for the company.",+ "created": "Time at which the company was created, in ISO 8601 format.",+ "customFields": "Custom fields associated with the company.",+ "domain": "The company's domain.",+ "memberCount": "The number of users associated with the company.",+ "monthlySpend": "The company's monthly spend.",+ "name": "The company's name.",+ },+ },+ "posts": {+ "description": "A post is a piece of feedback (feature request, bug, idea) on a board.",+ "docs_url": "https://developers.canny.io/api-reference#posts",+ "columns": {+ "id": "A unique identifier for the post.",+ "author": "The user who authored the post.",+ "board": "The board the post is on.",+ "by": "The admin who created the post on behalf of a user, if any.",+ "category": "The category the post belongs to, if any.",+ "commentCount": "The number of comments on the post.",+ "created": "Time at which the post was created, in ISO 8601 format.",+ "details": "The post's body/description.",+ "eta": "The estimated time of delivery for the post.",+ "imageURLs": "Image URLs attached to the post.",+ "owner": "The admin who owns the post, if any.",+ "score": "The post's vote score.",+ "status": "The post's status (e.g. open, planned, in progress, complete, closed).",+ "statusChangedAt": "Time at which the post's status last changed, in ISO 8601 format.",+ "tags": "The tags applied to the post.",+ "title": "The post's title.",+ "url": "The URL to the post's page.",+ "voteCount": "The number of votes the post has received.",+ },+ },+ "status_changes": {+ "description": "A record of a post's status changing (e.g. open → planned).",+ "docs_url": "https://developers.canny.io/api-reference#status_changes",+ "columns": {+ "id": "A unique identifier for the status change.",+ "changeComment": "The comment left by the admin when changing the status.",+ "changer": "The admin who changed the status.",+ "created": "Time at which the status change occurred, in ISO 8601 format.",+ "post": "The post whose status changed.",+ "status": "The new status the post was changed to.",+ },+ },+ "tags": {+ "description": "A tag that can be applied to posts on a board.",+ "docs_url": "https://developers.canny.io/api-reference#tags",+ "columns": {+ "id": "A unique identifier for the tag.",+ "board": "The board the tag belongs to.",+ "created": "Time at which the tag was created, in ISO 8601 format.",+ "name": "The name of the tag.",+ "postCount": "The number of posts with this tag.",+ "url": "The URL to the tag's page.",+ },+ },+ "users": {+ "description": "A user who has interacted with your Canny boards.",+ "docs_url": "https://developers.canny.io/api-reference#users",+ "columns": {+ "id": "A unique identifier for the user.",+ "created": "Time at which the user was created, in ISO 8601 format.",+ "email": "The user's email address.",+ "isAdmin": "Whether the user is an admin of the Canny workspace.",+ "name": "The user's name.",+ "url": "The URL to the user's profile.",+ "userID": "The unique identifier you assigned to the user via the widget/SSO.",+ "avatarURL": "The URL to the user's avatar image.",+ "companies": "The companies the user belongs to.",+ "customFields": "Custom fields associated with the user.",+ "lastActivity": "Time of the user's last activity, in ISO 8601 format.",+ },+ },+ "votes": {+ "description": "A vote cast by a user on a post.",+ "docs_url": "https://developers.canny.io/api-reference#votes",+ "columns": {+ "id": "A unique identifier for the vote.",+ "board": "The board the voted-on post belongs to.",+ "by": "The admin who cast the vote on behalf of a user, if any.",+ "created": "Time at which the vote was cast, in ISO 8601 format.",+ "post": "The post that was voted on.",+ "voter": "The user who cast the vote.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/canny/settings.py b/posthog/temporal/data_imports/sources/canny/settings.pynew file mode 100644index 000000000000..9da3ffef227b--- /dev/null+++ b/posthog/temporal/data_imports/sources/canny/settings.py@@ -0,0 +1,46 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.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).+++@dataclass+class CannyEndpointConfig:+ # Path under the API base (https://canny.io/api). Canny still serves every+ # resource we sync from its v1 list endpoints.+ path: str+ # Top-level key in the 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.+ paginated: bool = True+ # Stable creation timestamp present on every Canny object — safe to partition on+ # 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"])+++CANNY_ENDPOINTS: dict[str, CannyEndpointConfig] = {+ "boards": CannyEndpointConfig(path="/v1/boards/list", data_key="boards", paginated=False),+ "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"),+ "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"),+ "votes": CannyEndpointConfig(path="/v1/votes/list", data_key="votes"),+}++ENDPOINTS = tuple(CANNY_ENDPOINTS.keys())++# No endpoint exposes a server-side updated-since filter, so no stream is incremental.+# Kept for parity with other sources and for the (empty) per-endpoint advertised options.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in CANNY_ENDPOINTS}diff --git a/posthog/temporal/data_imports/sources/canny/source.py b/posthog/temporal/data_imports/sources/canny/source.pyindex bfca1272b6b5..8a990ec06840 100644--- a/posthog/temporal/data_imports/sources/canny/source.py+++ b/posthog/temporal/data_imports/sources/canny/source.py@@ -1,20 +1,33 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.canny.canny import (+ CannyResumeConfig,+ canny_source,+ validate_credentials as validate_canny_credentials,+)+from posthog.temporal.data_imports.sources.canny.settings import CANNY_ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import CannySourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class CannySource(SimpleSource[CannySourceConfig]):+class CannySource(ResumableSource[CannySourceConfig, CannyResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CANNY@@ -25,7 +38,93 @@ class CannySource(SimpleSource[CannySourceConfig]):name=SchemaExternalDataSourceType.CANNY,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Canny",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Canny API key to sync your Canny feedback, posts, and roadmap data into the PostHog Data warehouse.++Find your secret API key under **Settings → API** in your Canny dashboard.""",iconPath="/static/services/canny.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/canny",unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ invalid_key_message = (+ "Your Canny API key is invalid or has been revoked. Find your secret API key under "+ "Settings → API in your Canny dashboard, then reconnect."+ )+ return {+ # Canny reports a bad API key either via an `{"error": ...}` body (raised as an HTTPError+ # carrying the error text) or a 401/403 status. Match the stable host, not the per-request+ # path/params. The exact wording is API-version dependent, so match the broad signals.+ "invalid API key": invalid_key_message,+ "401 Client Error: Unauthorized for url: https://canny.io": invalid_key_message,+ "403 Client Error: Forbidden for url: https://canny.io": invalid_key_message,+ }++ def get_schemas(+ self,+ config: CannySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # No Canny list endpoint exposes a server-side updated-since filter, so every stream is+ # full refresh only — neither incremental nor append is offered.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in CANNY_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: CannySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_canny_credentials(config.api_key):+ return True, None++ return False, "Invalid Canny API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CannyResumeConfig]:+ return ResumableSourceManager[CannyResumeConfig](inputs, CannyResumeConfig)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.canny.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def source_for_pipeline(+ self,+ config: CannySourceConfig,+ resumable_source_manager: ResumableSourceManager[CannyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return canny_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/canny/tests/test_canny.py b/posthog/temporal/data_imports/sources/canny/tests/test_canny.pynew file mode 100644index 000000000000..9dbc1102aa07--- /dev/null+++ b/posthog/temporal/data_imports/sources/canny/tests/test_canny.py@@ -0,0 +1,222 @@+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests++from posthog.temporal.data_imports.sources.canny.canny import (+ PAGE_SIZE,+ CannyResumeConfig,+ CannyRetryableError,+ _build_body,+ _extract_records,+ _handle_response,+ canny_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.canny.settings import CANNY_ENDPOINTS, ENDPOINTS, CannyEndpointConfig+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++_POSTS = CANNY_ENDPOINTS["posts"]+_BOARDS = CANNY_ENDPOINTS["boards"]+++def _resp(body: Any, status: int = 200) -> Any:+ response = MagicMock()+ response.status_code = status+ response.ok = 200 <= status < 400+ response.json.return_value = body+ response.text = str(body)+ return response+++def _full_page(key: str) -> dict[str, Any]:+ return {key: [{"id": str(i)} for i in range(PAGE_SIZE)], "hasMore": True}+++def _drive(+ endpoint: str, manager: Any, responses: list[Any]+) -> tuple[list[dict[str, Any]], list[list[dict[str, Any]]]]:+ """Drive ``get_rows`` with a mocked tracked session, returning (posted_bodies, yielded_batches)."""+ posted_bodies: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_post(url: str, data: Any = None, timeout: Any = None, **_kwargs: Any) -> Any:+ posted_bodies.append(dict(data or {}))+ return next(response_iter)++ with patch("posthog.temporal.data_imports.sources.canny.canny.make_tracked_session") as MockSession:+ MockSession.return_value.post.side_effect = fake_post+ batches = list(get_rows(api_key="k", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=manager))++ return posted_bodies, batches+++class TestBuildBody:+ def test_paginated_includes_skip_and_limit(self) -> None:+ assert _build_body("k", _POSTS, skip=200) == {"apiKey": "k", "skip": 200, "limit": PAGE_SIZE}++ def test_unpaginated_only_api_key(self) -> None:+ # boards/list takes no pagination params.+ assert _build_body("k", _BOARDS, skip=0) == {"apiKey": "k"}+++class TestExtractRecords:+ def test_extracts_configured_key(self) -> None:+ config = CannyEndpointConfig(path="/v1/x/list", data_key="statusChanges")+ assert _extract_records({"statusChanges": [{"id": "1"}]}, config) == [{"id": "1"}]++ @pytest.mark.parametrize("body", [{}, {"posts": None}, {"posts": {"id": "1"}}, {"other": [{"id": "1"}]}])+ def test_missing_or_non_list_returns_empty(self, body: dict[str, Any]) -> None:+ assert _extract_records(body, _POSTS) == []+++class TestHandleResponse:+ # Exercise the per-response classification directly, so a single attempt's behaviour can be+ # asserted without driving the tenacity retry loop (and its real backoff sleeps).+ def _handle(self, response: Any) -> dict[str, Any]:+ return _handle_response(response, "https://canny.io/api/v1/posts/list", MagicMock())++ @pytest.mark.parametrize("status", [429, 500, 503])+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:+ with pytest.raises(CannyRetryableError):+ self._handle(_resp({}, status=status))++ @pytest.mark.parametrize("status", [400, 401, 403])+ def test_client_errors_raise_http_error(self, status: int) -> None:+ response = _resp({}, status=status)+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} Client Error", response=response)+ with pytest.raises(requests.HTTPError):+ self._handle(response)++ def test_error_body_on_200_raises_http_error(self) -> None:+ # Canny can return 200 with an {"error": ...} body for a bad API key.+ with pytest.raises(requests.HTTPError, match="invalid API key"):+ self._handle(_resp({"error": "invalid API key"}))++ def test_success_returns_body(self) -> None:+ assert self._handle(_resp({"posts": [], "hasMore": False})) == {"posts": [], "hasMore": False}+++class TestGetRows:+ def test_paginates_until_has_more_false_and_saves_after_each_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _full_page("posts"),+ _full_page("posts"),+ {"posts": [{"id": "final"}], "hasMore": False},+ ]+ posted, batches = _drive("posts", manager, [_resp(r) for r in responses])++ assert [b.get("skip") for b in posted] == [0, PAGE_SIZE, PAGE_SIZE * 2]+ assert len(batches) == 3+ # State is saved after each non-terminal page so a crash re-yields rather than skips.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [CannyResumeConfig(skip=PAGE_SIZE), CannyResumeConfig(skip=PAGE_SIZE * 2)]++ def test_resume_seeds_skip_from_saved_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = CannyResumeConfig(skip=PAGE_SIZE * 2)++ posted, batches = _drive("posts", manager, [_resp({"posts": [{"id": "x"}], "hasMore": False})])++ assert posted[0].get("skip") == PAGE_SIZE * 2+ manager.load_state.assert_called_once()+ assert len(batches) == 1++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, batches = _drive("posts", manager, [_resp({"posts": [{"id": "only"}], "hasMore": False})])++ assert len(batches) == 1+ manager.save_state.assert_not_called()++ def test_unpaginated_endpoint_fetches_once(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ # boards/list has no hasMore flag; a single fetch must terminate the loop.+ posted, batches = _drive("boards", manager, [_resp({"boards": [{"id": "b1"}]})])++ assert len(posted) == 1+ assert "skip" not in posted[0]+ assert batches == [[{"id": "b1"}]]+ manager.save_state.assert_not_called()++ def test_empty_page_yields_nothing(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ _, batches = _drive("posts", manager, [_resp({"posts": [], "hasMore": False})])++ assert batches == []+ manager.save_state.assert_not_called()++ def test_error_body_propagates(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with pytest.raises(requests.HTTPError):+ _drive("posts", manager, [_resp({"error": "invalid API key"})])++ def test_registers_api_key_for_redaction(self) -> None:+ # The secret rides in the POST body through the tracked transport; it must be redacted so it+ # never lands in HTTP logs/samples.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patch("posthog.temporal.data_imports.sources.canny.canny.make_tracked_session") as MockSession:+ MockSession.return_value.post.return_value = _resp({"posts": [], "hasMore": False})+ list(get_rows(api_key="secret", endpoint="posts", logger=MagicMock(), resumable_source_manager=manager))++ MockSession.assert_called_once_with(redact_values=("secret",))+++class TestValidateCredentials:+ def _validate(self, response: Any = None, raises: Exception | None = None) -> bool:+ with patch("posthog.temporal.data_imports.sources.canny.canny.make_tracked_session") as MockSession:+ post = MockSession.return_value.post+ if raises is not None:+ post.side_effect = raises+ else:+ post.return_value = response+ return validate_credentials("k")++ def test_valid_key(self) -> None:+ assert self._validate(_resp({"boards": []})) is True++ def test_error_body_is_invalid(self) -> None:+ assert self._validate(_resp({"error": "invalid API key"})) is False++ def test_non_ok_is_invalid(self) -> None:+ assert self._validate(_resp({}, status=401)) is False++ def test_network_error_is_invalid(self) -> None:+ assert self._validate(raises=requests.ConnectionError("boom")) is False++ def test_registers_api_key_for_redaction(self) -> None:+ with patch("posthog.temporal.data_imports.sources.canny.canny.make_tracked_session") as MockSession:+ MockSession.return_value.post.return_value = _resp({"boards": []})+ validate_credentials("secret")++ MockSession.assert_called_once_with(redact_values=("secret",))+++class TestCannySource:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_source_response_shape(self, endpoint: str) -> None:+ response = canny_source(+ api_key="k", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # Every Canny object carries a stable `created` timestamp we partition on.+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created"]diff --git a/posthog/temporal/data_imports/sources/canny/tests/test_canny_source.py b/posthog/temporal/data_imports/sources/canny/tests/test_canny_source.pynew file mode 100644index 000000000000..8024270f4990--- /dev/null+++ b/posthog/temporal/data_imports/sources/canny/tests/test_canny_source.py@@ -0,0 +1,139 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.canny.canny import CannyResumeConfig+from posthog.temporal.data_imports.sources.canny.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.canny.source import CannySource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import CannySourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "posts",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestCannySource:+ def setup_method(self) -> None:+ self.source = CannySource()+ self.team_id = 123+ self.config = CannySourceConfig(api_key="test-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CANNY++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Canny"+ assert config.label == "Canny"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Canny ships hidden for now — it must stay behind unreleasedSource until released.+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/canny.png"++ assert len(config.fields) == 1+ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ @pytest.mark.parametrize(+ "expected_key",+ [+ "invalid API key",+ "401 Client Error: Unauthorized for url: https://canny.io",+ "403 Client Error: Forbidden for url: https://canny.io",+ ],+ )+ def test_non_retryable_errors(self, expected_key: str) -> None:+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_all_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {s.name for s in schemas} == set(ENDPOINTS)+ # Canny exposes no server-side updated-since filter, so every stream is full refresh only.+ assert all(not s.supports_incremental for s in schemas)+ assert all(not s.supports_append for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["posts"])+ assert len(schemas) == 1+ assert schemas[0].name == "posts"++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @pytest.mark.parametrize(+ ("mock_return", "expected_valid", "expected_message"),+ [+ (True, True, None),+ (False, False, "Invalid Canny API key"),+ ],+ )+ @mock.patch("posthog.temporal.data_imports.sources.canny.source.validate_canny_credentials")+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ mock_return: bool,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("test-key")++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CannyResumeConfig++ @mock.patch("posthog.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")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="test-key",+ endpoint="comments",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ # Every advertised endpoint should carry a curated description so the warehouse can describe+ # it deterministically instead of paying for per-team LLM enrichment.+ assert set(ENDPOINTS).issubset(descriptions.keys())+ assert all(entry.get("description") for entry in descriptions.values())diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 8d2940ff0aef..216cd1af009a 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -545,7 +545,7 @@ class CampaynSourceConfig(config.Config):@config.configclass CannySourceConfig(config.Config):- pass+ api_key: str@config.config