: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 knock import source (#72614)
Tom Owers9ae0dee1b1e9
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 94ed03b4d693..dbea0d701c8e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -308,6 +308,7 @@ the row lists both.| kernel | HTTP | requests | ✅ || klaus | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ |+| knock | HTTP | requests + `rest_source.RESTClient` | ✅ || koyeb | HTTP | requests | ✅ || kong_konnect | HTTP | requests | ✅ || kubecost | HTTP | requests | ✅ |@@ -794,7 +795,6 @@ doesn't conflict with concurrent PRs.- kisi- kissmetrics- klarna-- knock- kommo- koyeb- kyvediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knock.pyindex 8229382aac1e..8305e63ebdec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knock.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knock.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass KnockSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/canonical_descriptions.pynew file mode 100644index 000000000000..2040c99cccc2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/canonical_descriptions.py@@ -0,0 +1,73 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "messages": {+ "description": "A notification delivered (or attempted) to a single recipient on a specific channel, with delivery and engagement status.",+ "docs_url": "https://docs.knock.app/api-reference/messages/list",+ "columns": {+ "id": "The unique identifier for the message.",+ "channel_id": "The ID of the channel the message was sent through.",+ "recipient": "The recipient of the message: a user ID string or an object reference.",+ "recipient_snapshot": "Snapshot of the recipient's contact information at send time; null for non-email channels.",+ "status": "The delivery status of the message (e.g. queued, sent, delivered, undelivered, bounced).",+ "engagement_statuses": "Engagement statuses recorded for the message (e.g. seen, read, interacted, link_clicked).",+ "tenant": "The ID of the tenant associated with the message, when provided on the trigger.",+ "workflow": "The key of the workflow that generated the message.",+ "source": "The workflow or guide that triggered the message, including its key and version.",+ "data": "Trigger data the message was generated with, merged with any fetch-function data.",+ "metadata": "Additional metadata associated with the message.",+ "actors": "Actors associated with the message (up to 10 when produced from a batch).",+ "inserted_at": "Timestamp when the message was created.",+ "updated_at": "Timestamp when the message was last updated.",+ "archived_at": "Timestamp when the message was archived.",+ "read_at": "Timestamp when the message was marked as read.",+ "seen_at": "Timestamp when the message was marked as seen.",+ "clicked_at": "Timestamp when the message was clicked.",+ "interacted_at": "Timestamp when the message was interacted with.",+ "link_clicked_at": "Timestamp when a link in the message was clicked.",+ "scheduled_at": "Timestamp when the message was scheduled to be sent.",+ },+ },+ "users": {+ "description": "A recipient identified to Knock, with the profile properties used to notify them.",+ "docs_url": "https://docs.knock.app/api-reference/users/list",+ "columns": {+ "id": "The unique identifier of the user in your environment.",+ "name": "The display name of the user.",+ "email": "The email address of the user.",+ "phone_number": "The E.164 phone number of the user, required to send SMS messages.",+ "avatar": "URL to the avatar image of the user.",+ "timezone": "The IANA timezone of the user, used for recurring schedules.",+ "created_at": "Timestamp when the user was created; may be null.",+ "updated_at": "Timestamp when the user was last updated.",+ },+ },+ "tenants": {+ "description": "A tenant used to scope notifications, preferences, and branding to a group of users (typically one of your customers).",+ "docs_url": "https://docs.knock.app/api-reference/tenants/list",+ "columns": {+ "id": "The unique identifier of the tenant.",+ "name": "The display name of the tenant.",+ "settings": "Tenant settings, including branding and the preference set applied to its users.",+ },+ },+ "workflow_recipient_runs": {+ "description": "An individual execution of a workflow for a specific recipient, with its trigger source and status.",+ "docs_url": "https://docs.knock.app/api-reference/workflow_recipient_runs/list",+ "columns": {+ "id": "The unique identifier for the workflow recipient run.",+ "workflow": "The key of the workflow that was executed.",+ "workflow_run_id": "The identifier of the top-level workflow run shared across all recipients of a single trigger.",+ "recipient": "The recipient the workflow ran for: a user ID string or an object reference.",+ "actor": "The actor that triggered the run, when one was provided.",+ "status": "The current status of the run (queued, processing, paused, completed, or cancelled).",+ "trigger_source": "How the workflow was triggered (e.g. api, audience, schedule, broadcast, workflow_step).",+ "error_count": "The number of errors encountered during the run.",+ "tenant": "The ID of the tenant associated with the run, when one was provided.",+ "inserted_at": "Timestamp when the run was created.",+ "updated_at": "Timestamp when the run was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/knock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/knock.pynew file mode 100644index 000000000000..5b5b418bdbdd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/knock.py@@ -0,0 +1,150 @@+import dataclasses+from datetime import datetime+from typing import Any, Optional++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.knock.settings import (+ ENDPOINTS_CONFIG,+ KNOCK_BASE_URL,+ KNOCK_PAGE_SIZE,+)++DEFAULT_INCREMENTAL_START = "1970-01-01T00:00:00Z"+++class KnockResumeConfig:+ after: str+++def _to_iso8601(value: Any) -> str:+ if isinstance(value, datetime):+ return value.isoformat()+ return str(value)+++def get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:+ config = ENDPOINTS_CONFIG[endpoint]++ params: dict[str, Any] = {"page_size": KNOCK_PAGE_SIZE}+ if should_use_incremental_field and config.incremental_param and config.incremental_fields:+ params[config.incremental_param] = {+ "type": "incremental",+ "cursor_path": config.incremental_fields[0]["field"],+ "initial_value": DEFAULT_INCREMENTAL_START,+ "convert": _to_iso8601,+ }++ return {+ "name": endpoint,+ "table_name": endpoint,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": config.data_selector,+ # Fail loud if Knock ever changes the response envelope key instead of+ # silently syncing 0 rows.+ "data_selector_required": True,+ },+ "table_format": "delta",+ }+++def knock_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[KnockResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+) -> SourceResponse:+ endpoint_config = ENDPOINTS_CONFIG[endpoint]++ config: RESTAPIConfig = {+ "client": {+ "base_url": KNOCK_BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "headers": {"Accept": "application/json"},+ "paginator": JSONResponseCursorPaginator(cursor_path="page_info.after", cursor_param="after"),+ },+ "resource_defaults": {},+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"cursor": resume_config.after}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's a next page to resume to; the Redis TTL+ # handles cleanup on completion.+ if state and state.get("cursor"):+ resumable_source_manager.save_state(KnockResumeConfig(after=str(state["cursor"])))++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ has_partition_key = endpoint_config.partition_key is not None++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=list(endpoint_config.primary_keys),+ partition_count=1 if has_partition_key else None,+ partition_size=1 if has_partition_key else None,+ partition_mode="datetime" if has_partition_key else None,+ partition_format="month" if has_partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ sort_mode=endpoint_config.sort_mode,+ )+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ session = make_tracked_session(redact_values=(api_key,))+ res = session.get(+ f"{KNOCK_BASE_URL}/v1/users",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ params={"page_size": 1},+ timeout=30,+ )++ if res.status_code == 200:+ return True, None++ if res.status_code in (401, 403):+ # Knock returns {"code": "api_key_invalid", "message": "..."} on auth failures.+ try:+ message = res.json().get("message")+ except Exception:+ message = None+ return False, message or "Invalid Knock API key"++ return False, f"Knock API returned an unexpected response (HTTP {res.status_code})"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/settings.pynew file mode 100644index 000000000000..8be0f82aa0a4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/settings.py@@ -0,0 +1,69 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++KNOCK_BASE_URL = "https://api.knock.app"++# Knock caps `page_size` at 50 on every list endpoint.+KNOCK_PAGE_SIZE = 50+++@dataclass(frozen=True)+class KnockEndpointConfig:+ path: str+ # Knock wraps list responses in `entries` on most endpoints but `items` on+ # messages and workflow recipient runs (per the vendor OpenAPI spec).+ data_selector: str+ primary_keys: tuple[str, ...] = ("id",)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Request param carrying the server-side lower-bound timestamp filter.+ incremental_param: str | None = None+ # Stable datetime field to partition on; None disables partitioning.+ partition_key: str | None = None+ sort_mode: SortMode = "desc"+++# Knock's list endpoints document "most recent first" ordering where they state one at+# all and accept no sort param, so every endpoint declares `sort_mode="desc"` — the+# pipeline then persists the incremental watermark only when a sync completes instead+# of checkpointing per batch on a newest-first stream.+ENDPOINTS_CONFIG: dict[str, KnockEndpointConfig] = {+ # Message delivery log — the highest-volume stream. `inserted_at[gte]` is a+ # documented server-side filter, so incremental sync genuinely reduces pages.+ "messages": KnockEndpointConfig(+ path="/v1/messages",+ data_selector="items",+ incremental_fields=[incremental_field("inserted_at")],+ incremental_param="inserted_at[gte]",+ partition_key="inserted_at",+ ),+ # Identified recipients. No server-side updated-since filter exists, so full+ # refresh only. `created_at` is nullable on users, so no partition key.+ "users": KnockEndpointConfig(+ path="/v1/users",+ data_selector="entries",+ ),+ # Tenants (per-customer notification scoping). Small table, no server-side+ # timestamp filter — full refresh only.+ "tenants": KnockEndpointConfig(+ path="/v1/tenants",+ data_selector="entries",+ ),+ # Per-recipient workflow executions. `starting_at` is a documented server-side+ # filter on when the run started, which tracks `inserted_at`.+ "workflow_recipient_runs": KnockEndpointConfig(+ path="/v1/workflow_recipient_runs",+ data_selector="items",+ incremental_fields=[incremental_field("inserted_at")],+ incremental_param="starting_at",+ partition_key="inserted_at",+ ),+}++ENDPOINTS = tuple(ENDPOINTS_CONFIG.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in ENDPOINTS_CONFIG.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/source.pyindex e4fb242340c9..f28554f1e49c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/source.py@@ -1,30 +1,121 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.knock import KnockSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.knock.knock import (+ KnockResumeConfig,+ knock_source,+ validate_credentials as validate_knock_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.knock.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class KnockSource(SimpleSource[KnockSourceConfig]):+class KnockSource(ResumableSource[KnockSourceConfig, KnockResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://docs.knock.app/api-reference/overview"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.KNOCK+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your Knock API key is invalid or has been revoked. Please generate a new secret key in the Knock dashboard and reconnect.",+ "403 Client Error: Forbidden for url": "Your Knock API key does not have access to this resource. Please check the key belongs to the right environment.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.knock.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: KnockSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: KnockSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_knock_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KnockResumeConfig]:+ return ResumableSourceManager[KnockResumeConfig](inputs, KnockResumeConfig)++ def source_for_pipeline(+ self,+ config: KnockSourceConfig,+ resumable_source_manager: ResumableSourceManager[KnockResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return knock_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.KNOCK,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Knock",+ caption="Use the secret API key (starts with `sk_`) for the environment you want to import from. You can find it in the Knock dashboard under **Developers → API keys**. Knock API keys are scoped to a single environment.",+ docsUrl="https://posthog.com/docs/cdp/sources/knock",iconPath="/static/services/knock.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ keywords=["notifications"],+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Secret API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="sk_...",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock.pynew file mode 100644index 000000000000..74e334ff12d0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock.py@@ -0,0 +1,207 @@+import json+from collections.abc import Iterable+from datetime import datetime+from typing import Any, Optional, cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.knock.knock import (+ KnockResumeConfig,+ get_resource,+ knock_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.knock.settings import ENDPOINTS_CONFIG+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _page(endpoint: str, rows: list[dict[str, Any]], after: str | None) -> Response:+ selector = ENDPOINTS_CONFIG[endpoint].data_selector+ return _make_http_response({selector: rows, "page_info": {"after": after, "before": None, "page_size": 50}})+++class TestGetResource:+ @parameterized.expand(+ [+ ("messages", "inserted_at[gte]"),+ ("workflow_recipient_runs", "starting_at"),+ ]+ )+ def test_incremental_uses_endpoint_specific_server_filter(self, endpoint: str, expected_param: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=True)+ params = cast(dict[str, Any], cast(dict[str, Any], resource["endpoint"])["params"])+ assert params[expected_param]["type"] == "incremental"+ assert params[expected_param]["cursor_path"] == "inserted_at"+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}++ @parameterized.expand([("messages",), ("users",), ("tenants",), ("workflow_recipient_runs",)])+ def test_full_refresh_sends_no_timestamp_filter(self, endpoint: str) -> None:+ resource = get_resource(endpoint, should_use_incremental_field=False)+ params = cast(dict[str, Any], cast(dict[str, Any], resource["endpoint"])["params"])+ assert set(params) == {"page_size"}+ assert resource["write_disposition"] == "replace"+++class TestKnockSourceTransport:+ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ ) -> tuple[SourceResponse, list[dict[str, Any]], list[dict[str, Any]]]:+ # Capture shallow copies of request.params at send-time: the Request object is+ # mutated in place by the paginator between pages.+ sent_params: 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 {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source_response = knock_source(+ api_key="sk_test",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+ rows = [row for chunk in cast(Iterable[Any], source_response.items()) for row in chunk]+ return source_response, sent_params, rows++ @parameterized.expand(+ [+ # Messages and workflow recipient runs wrap rows in `items`; users and+ # tenants wrap them in `entries` — a swapped selector syncs 0 rows.+ ("messages",),+ ("users",),+ ]+ )+ def test_rows_extracted_from_endpoint_envelope(self, endpoint: str) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_page(endpoint, [{"id": "a"}, {"id": "b"}], after=None)]+ _, _, rows = self._drive(endpoint, manager, responses)++ assert [row["id"] for row in rows] == ["a", "b"]++ def test_fresh_run_pages_on_after_cursor_and_saves_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _page("messages", [{"id": "m1"}], after="cursor-1"),+ _page("messages", [{"id": "m2"}], after="cursor-2"),+ _page("messages", [{"id": "m3"}], after=None),+ ]+ _, sent_params, rows = self._drive("messages", manager, responses)++ assert [p.get("after") for p in sent_params] == [None, "cursor-1", "cursor-2"]+ # page_size rides along on every request.+ assert all(p.get("page_size") == 50 for p in sent_params)+ assert [row["id"] for row in rows] == ["m1", "m2", "m3"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [KnockResumeConfig(after="cursor-1"), KnockResumeConfig(after="cursor-2")]++ def test_resume_seeds_paginator_with_saved_cursor(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = KnockResumeConfig(after="cursor-resumed")++ responses = [_page("messages", [{"id": "m9"}], after=None)]+ _, sent_params, _ = self._drive("messages", manager, responses)++ assert [p.get("after") for p in sent_params] == ["cursor-resumed"]++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ self._drive("messages", manager, [_page("messages", [{"id": "only"}], after=None)])++ manager.save_state.assert_not_called()++ def test_incremental_run_sends_watermark_as_iso8601(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_page("messages", [{"id": "m1", "inserted_at": "2026-06-01T00:00:00Z"}], after=None)]+ _, sent_params, _ = self._drive(+ "messages",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 5, 1, 12, 30),+ )++ assert sent_params[0]["inserted_at[gte]"] == "2026-05-01T12:30:00"++ @parameterized.expand(+ [+ ("messages", ["inserted_at"]),+ ("workflow_recipient_runs", ["inserted_at"]),+ ("users", None),+ ("tenants", None),+ ]+ )+ def test_source_response_partitioning_and_sort_mode(self, endpoint: str, partition_keys: list[str] | None) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ source_response, _, _ = self._drive(endpoint, manager, [_page(endpoint, [], after=None)])++ assert source_response.primary_keys == ["id"]+ # Knock lists return newest-first, so the pipeline must not checkpoint the+ # watermark per batch.+ assert source_response.sort_mode == "desc"+ assert source_response.partition_keys == partition_keys+ assert source_response.partition_mode == ("datetime" if partition_keys else None)+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, {}, (True, None)),+ (+ "invalid_key",+ 401,+ {"code": "api_key_invalid", "message": "The API key you supplied is invalid"},+ (False, "The API key you supplied is invalid"),+ ),+ ("auth_error_without_body", 401, {}, (False, "Invalid Knock API key")),+ ("server_error", 500, {}, (False, "Knock API returned an unexpected response (HTTP 500)")),+ ]+ )+ def test_status_mapping(+ self, _name: str, status_code: int, body: dict[str, Any], expected: tuple[bool, str | None]+ ) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.knock.knock.make_tracked_session"+ ) as mock_make_session:+ mock_make_session.return_value.get.return_value = _make_http_response(body, status_code)+ assert validate_credentials("sk_test") == expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock_source.pynew file mode 100644index 000000000000..795a598fbd1c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knock/tests/test_knock_source.py@@ -0,0 +1,122 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.knock.knock import KnockResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.knock.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.knock.source import KnockSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _config(api_key: str = "sk_test") -> Any:+ config = MagicMock()+ config.api_key = api_key+ return config+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert KnockSource().source_type == ExternalDataSourceType.KNOCK++ def test_config_is_visible_and_alpha(self) -> None:+ config = KnockSource().get_source_config+ # A finished source must not be hidden from users.+ assert getattr(config, "unreleasedSource", None) in (None, False)+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.category == DataWarehouseSourceCategory.MARKETING___EMAIL+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/knock"++ def test_fields(self) -> None:+ fields = {f.name: f for f in KnockSource().get_source_config.fields if isinstance(f, SourceFieldInputConfig)}+ assert set(fields) == {"api_key"}+ assert fields["api_key"].required is True+ assert fields["api_key"].secret is True+++class TestGetSchemas:+ def test_only_server_side_filtered_endpoints_are_incremental(self) -> None:+ schemas = {s.name: s for s in KnockSource().get_schemas(_config(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)+ # Only messages (inserted_at[gte]) and workflow_recipient_runs (starting_at)+ # have a genuine server-side timestamp filter.+ assert {name for name, s in schemas.items() if s.supports_incremental} == {+ "messages",+ "workflow_recipient_runs",+ }+ assert [f["field"] for f in schemas["messages"].incremental_fields] == ["inserted_at"]+ assert [f["field"] for f in schemas["workflow_recipient_runs"].incremental_fields] == ["inserted_at"]++ def test_names_filter(self) -> None:+ schemas = KnockSource().get_schemas(_config(), team_id=1, names=["users", "tenants"])+ assert {s.name for s in schemas} == {"users", "tenants"}++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog (no I/O) — public docs render the table list.+ assert KnockSource.lists_tables_without_credentials is True+ tables = {t["name"]: t for t in KnockSource().get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert tables["users"]["sync_methods"] == ["Full refresh"]+ assert "Incremental" in tables["messages"]["sync_methods"]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", (True, None)),+ ("invalid", (False, "The API key you supplied is invalid")),+ ]+ )+ def test_plumbs_transport_result(self, _name: str, result: tuple[bool, str | None]) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.knock.source.validate_knock_credentials",+ return_value=result,+ ) as mocked:+ assert KnockSource().validate_credentials(_config(), team_id=1) == result+ mocked.assert_called_once_with("sk_test")+++class TestResumableWiring:+ def test_get_resumable_source_manager_binds_data_class(self) -> None:+ inputs = MagicMock()+ inputs.logger = MagicMock()+ manager = KnockSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is KnockResumeConfig++ @parameterized.expand(+ [+ ("incremental", True, "2026-01-01"),+ # A stale watermark must not leak into a full-refresh run.+ ("full_refresh", False, None),+ ]+ )+ def test_source_for_pipeline_plumbs_arguments(+ self, _name: str, should_use_incremental_field: bool, expected_last_value: Any+ ) -> None:+ inputs = MagicMock()+ inputs.schema_name = "messages"+ inputs.team_id = 42+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = should_use_incremental_field+ inputs.db_incremental_field_last_value = "2026-01-01"+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.knock.source.knock_source"+ ) as mocked:+ KnockSource().source_for_pipeline(_config(), manager, inputs)++ mocked.assert_called_once_with(+ api_key="sk_test",+ endpoint="messages",+ team_id=42,+ job_id="job-1",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=expected_last_value,+ )