Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add Kickscale import source (#84291)

Tom Owersb24c80af8a87
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kickscale.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kickscale.py
index 038e916bcd70..e41cc8a2830c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kickscale.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kickscale.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class KickscaleSourceConfig(config.Config):
- pass
+ api_key: str
+ client_id: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/canonical_descriptions.py
new file mode 100644
index 000000000000..9cf367292ca4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/canonical_descriptions.py
@@ -0,0 +1,61 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_SWAGGER_URL = "https://api.kickscale.com/swagger"
+
+# Meetings and calls share the same DTO shape (id, timestamps, participants, metrics, insights,
+# CRM references, ...) apart from a few endpoint-specific fields (calls add caller/callee/
+# direction; meetings add participantEmails/metadata).
+_SHARED_COLUMNS = {
+ "id": "Unique identifier for the record.",
+ "createdAt": "When the record was created in Kickscale.",
+ "updatedAt": "When the record was last updated in Kickscale.",
+ "clientId": "Identifier of the Kickscale workspace (client) the record belongs to.",
+ "name": "Display name of the meeting or call.",
+ "date": "Start date and time of the meeting or call.",
+ "summary": "AI-generated summary of the conversation.",
+ "actionItems": "Action items extracted from the conversation.",
+ "participants": "Transcript participants detected in the recording.",
+ "userQuestions": "Questions asked by the Kickscale user during the conversation.",
+ "duration": "Duration of the recording, in seconds.",
+ "emailDraft": "AI-drafted follow-up email for the conversation.",
+ "feedback": "Feedback given on the meeting type's scored criteria.",
+ "metrics": "Talk-time and engagement metrics (speak ratio, questions, patience, words per minute, monologue).",
+ "type": "Meeting type configuration applied to this record.",
+ "insights": "AI-generated insights extracted from the conversation.",
+ "language": "Detected language of the transcript.",
+ "outcome": "Recorded outcome of the meeting or call.",
+ "comments": "Comments left on the record by Kickscale users.",
+ "rating": "Manual rating given to the record.",
+ "user": "Kickscale user who owns the record.",
+ "recordingRef": "Download URL for the recording. Only valid for 2 days.",
+ "transcript": "Full transcript of the conversation. Only populated when `expand` includes `meeting_transcript`.",
+ "crmReference": "Linked CRM record (deal, company, contact) this conversation is associated with.",
+ "customerDomains": "Email domains of external participants, used to associate the record with a customer.",
+ "businessEntities": "Deals and companies detected or linked to the record.",
+ "recordingConsent": "Recording consent status captured for the conversation.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "meetings": {
+ "description": "Analyzed video meetings (Zoom, Teams, Meet) recorded and transcribed by Kickscale.",
+ "docs_url": _SWAGGER_URL,
+ "columns": {
+ **_SHARED_COLUMNS,
+ "participantEmails": "Email addresses of all detected meeting participants.",
+ "metadata": "User-provided metadata attached to the meeting.",
+ },
+ },
+ "calls": {
+ "description": "Analyzed phone/dialer calls (Aircall, RingCentral, Genesys, HubSpot Calling) recorded and transcribed by Kickscale.",
+ "docs_url": _SWAGGER_URL,
+ "columns": {
+ **_SHARED_COLUMNS,
+ "caller": "Party that placed the call.",
+ "callee": "Party that received the call.",
+ "direction": "Call direction: inbound or outbound.",
+ "externalCallId": "Identifier of the call in the originating telephony/dialer system.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/kickscale.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/kickscale.py
new file mode 100644
index 000000000000..dafbdab1b11c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/kickscale.py
@@ -0,0 +1,216 @@
+from typing import Any, Optional
+
+from requests import PreparedRequest, Response
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+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.auth import AuthConfigBase
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+ IncrementalConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.settings import (
+ DEFAULT_PAGE_SIZE,
+ KICKSCALE_BASE_URL,
+ KICKSCALE_ENDPOINTS,
+)
+
+
+@frozen
+class KickscaleResumeConfig:
+ page: int
+
+
+class KickscaleAuth(AuthConfigBase):
+ """Kickscale requires two static headers together; either alone is rejected.
+
+ The generic auth types each carry a single credential header, so both are set here and both
+ reported as secret so the tracked session masks them wherever they surface in logs or
+ captured samples.
+ """
+
+ def __init__(self, api_key: str, client_id: str) -> None:
+ self.api_key = api_key
+ self.client_id = client_id
+
+ def __call__(self, request: PreparedRequest) -> PreparedRequest:
+ request.headers["api-key"] = self.api_key
+ request.headers["client-id"] = self.client_id
+ return request
+
+ def secret_values(self) -> tuple[str, ...]:
+ return tuple(value for value in (self.api_key, self.client_id) if value)
+
+
+class KickscalePageNumberPaginator(PageNumberPaginator):
+ """Kickscale's list responses carry no total-count field, so a full-strength page is the
+ only signal there's more to fetch; a short (or empty) page ends the sync."""
+
+ def __init__(self, page_size: int) -> None:
+ super().__init__(base_page=0, page_param="page")
+ self._page_size = page_size
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if self._has_next_page and data is not None and len(data) < self._page_size:
+ self._has_next_page = False
+
+ def __str__(self) -> str:
+ return f"KickscalePageNumberPaginator(page={self.page}, page_size={self._page_size})"
+
+
+def _format_kickscale_datetime(value: Any) -> str:
+ normalized_value = coerce_datetime_to_utc(value)
+ if normalized_value is None:
+ return str(value)
+ return normalized_value.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _incremental_window(cursor_path: str) -> IncrementalConfig:
+ # `startDate` returns meetings/calls on or after the given instant, and `sortingOrder`
+ # (set in get_resource) is pinned to ascending so rows arrive in cursor order for the
+ # pipeline's watermark checkpoint.
+ return {
+ "cursor_path": cursor_path,
+ "start_param": "startDate",
+ "initial_value": "1970-01-01T00:00:00Z",
+ "convert": _format_kickscale_datetime,
+ }
+
+
+def _client_config(api_key: str, client_id: str) -> ClientConfig:
+ return {
+ "base_url": KICKSCALE_BASE_URL,
+ "auth": KickscaleAuth(api_key=api_key, client_id=client_id),
+ "paginator": KickscalePageNumberPaginator(page_size=DEFAULT_PAGE_SIZE),
+ # Pin every request (and the api-key/client-id headers) to the Kickscale host and refuse
+ # to follow a 3xx, so a server-side redirect can never replay the credentials off-host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ }
+
+
+def get_resource(
+ endpoint: str,
+ should_use_incremental_field: bool,
+ incremental_field_name: str | None = None,
+) -> EndpointResource:
+ config = KICKSCALE_ENDPOINTS[endpoint]
+
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "params": {
+ "pageSize": DEFAULT_PAGE_SIZE,
+ "sortingOrder": "ascending",
+ # Without `expand`, the embedded user profile and transcript are omitted from
+ # every row.
+ "expand": "user_client_augmentation,meeting_transcript",
+ # `scopes` defaults to "external" only, silently dropping internal meetings from
+ # every list response unless "internal" is requested alongside it.
+ "scopes": "internal,external",
+ },
+ }
+
+ use_incremental = should_use_incremental_field and bool(config.incremental_fields)
+ if use_incremental:
+ endpoint_config["incremental"] = _incremental_window(
+ incremental_field_name or config.incremental_fields[0]["field"]
+ )
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_incremental else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+
+
+def kickscale_source(
+ api_key: str,
+ client_id: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[KickscaleResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = KICKSCALE_ENDPOINTS[endpoint]
+
+ config: RESTAPIConfig = {
+ "client": _client_config(api_key, client_id),
+ "resource_defaults": {},
+ "resources": [get_resource(endpoint, should_use_incremental_field, 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 = {"page": resume_config.page}
+
+ 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("page") is not None:
+ resumable_source_manager.save_state(KickscaleResumeConfig(page=int(state["page"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint_config.name,
+ items=lambda: resource,
+ primary_keys=endpoint_config.primary_key,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ # Meetings/calls carry full transcripts once expanded, so rows can be large — keep
+ # chunks smaller than the pipeline default to bound peak memory.
+ chunk_size=1000,
+ chunk_size_bytes=100 * 1024 * 1024,
+ )
+
+
+def validate_credentials(api_key: str, client_id: str) -> tuple[bool, str | None]:
+ response = make_tracked_session(redact_values=(api_key, client_id), allow_redirects=False).get(
+ f"{KICKSCALE_BASE_URL}/meetings",
+ headers={"api-key": api_key, "client-id": client_id},
+ params={"page": 0, "pageSize": 1},
+ timeout=10,
+ )
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 403:
+ return (
+ False,
+ "Kickscale rejected the API key and client ID. Check both values under "
+ "Settings > Integrations > API & Webhooks and reconnect.",
+ )
+ return False, f"Kickscale API returned an unexpected status code: {response.status_code}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/settings.py
new file mode 100644
index 000000000000..2695938e3cfb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/settings.py
@@ -0,0 +1,54 @@
+from dataclasses import field
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+# The OpenAPI document declares no `servers` entry, so the base URL is hardcoded.
+KICKSCALE_BASE_URL = "https://api.kickscale.com"
+
+# Kickscale documents a 20-row default page size with a maximum recommended 100. Responses are a
+# bare JSON array with no total-count field, so pagination stops once a page returns fewer than
+# this many rows.
+DEFAULT_PAGE_SIZE = 100
+
+# Comments, ratings, CRM links and re-analysis can land on a meeting/call after its `date`, and
+# the API has no updated-since filter — re-scan a trailing window on every incremental sync so
+# those late edits aren't missed (the merge dedupes on `id`).
+INCREMENTAL_LOOKBACK_SECONDS = 14 * 24 * 60 * 60
+
+
+@frozen
+class KickscaleEndpointConfig:
+ name: str
+ path: str
+ primary_key: list[str]
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ partition_key: str | None = None
+
+
+KICKSCALE_ENDPOINTS: dict[str, KickscaleEndpointConfig] = {
+ "meetings": KickscaleEndpointConfig(
+ name="meetings",
+ path="/meetings",
+ primary_key=["id"],
+ # `date` is the only field the API accepts a server-side filter on (`startDate` /
+ # `endDate`); it's the meeting's start time and doesn't move once the meeting happened.
+ incremental_fields=[incremental_field("date")],
+ partition_key="date",
+ ),
+ "calls": KickscaleEndpointConfig(
+ name="calls",
+ path="/calls",
+ primary_key=["id"],
+ incremental_fields=[incremental_field("date")],
+ partition_key="date",
+ ),
+}
+
+ENDPOINTS = tuple(KICKSCALE_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in KICKSCALE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/source.py
index f488ed35c5d5..10acdbe5af2b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/source.py
@@ -1,33 +1,145 @@
-from typing import cast
+from typing import Optional, cast
from 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.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.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kickscale import (
KickscaleSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.kickscale import (
+ KickscaleResumeConfig,
+ kickscale_source,
+ validate_credentials as validate_kickscale_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ INCREMENTAL_LOOKBACK_SECONDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class KickscaleSource(SimpleSource[KickscaleSourceConfig]):
+class KickscaleSource(ResumableSource[KickscaleSourceConfig, KickscaleResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # Kickscale's API has no versioned path segment, header, or query param — its OpenAPI
+ # document is labelled "1.0" but that isn't a value the client sends anywhere.
+ api_docs_url = "https://api.kickscale.com/swagger"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.KICKSCALE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "403 Client Error: Forbidden for url": "Kickscale rejected the API key and client ID. "
+ "Check both values under Settings > Integrations > API & Webhooks and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: KickscaleSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+ for schema in schemas:
+ # Comments, ratings, CRM links and re-analysis can land on a record after its
+ # `date`, and there's no updated-since filter to catch them otherwise.
+ schema.default_incremental_lookback_seconds = INCREMENTAL_LOOKBACK_SECONDS
+ return schemas
+
+ def validate_credentials(
+ self,
+ config: KickscaleSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_kickscale_credentials(config.api_key, config.client_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KickscaleResumeConfig]:
+ return ResumableSourceManager[KickscaleResumeConfig](inputs, KickscaleResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: KickscaleSourceConfig,
+ resumable_source_manager: ResumableSourceManager[KickscaleResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return kickscale_source(
+ api_key=config.api_key,
+ client_id=config.client_id,
+ 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,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.KICKSCALE,
category=DataWarehouseSourceCategory.SALES,
label="Kickscale",
+ caption="Sync analyzed meetings and calls from Kickscale. Find your API key and "
+ "client ID under Settings > Integrations > API & Webhooks in Kickscale "
+ "(requires a Configurator or Admin role). API keys expire after 1 year.",
+ docsUrl="https://posthog.com/docs/cdp/sources/kickscale",
iconPath="/static/services/kickscale.png",
+ releaseStatus=ReleaseStatus.ALPHA,
keywords=["revenue intelligence", "sales enablement", "conversation intelligence"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="client_id",
+ label="Client ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/tests/test_kickscale.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/tests/test_kickscale.py
new file mode 100644
index 000000000000..2f75b6f95127
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/tests/test_kickscale.py
@@ -0,0 +1,268 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, Mock, patch
+
+from parameterized import parameterized
+from requests import Request, Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.kickscale import (
+ KickscaleAuth,
+ KickscalePageNumberPaginator,
+ KickscaleResumeConfig,
+ _client_config,
+ _format_kickscale_datetime,
+ get_resource,
+ kickscale_source,
+ validate_credentials,
+)
+
+
+class TestKickscaleAuth:
+ def test_sets_both_headers(self) -> None:
+ auth = KickscaleAuth(api_key="key-1", client_id="client-1")
+ request = Request(method="GET", url="https://api.kickscale.com/meetings").prepare()
+
+ auth(request)
+
+ assert request.headers["api-key"] == "key-1"
+ assert request.headers["client-id"] == "client-1"
+
+ def test_secret_values_reports_both_credentials(self) -> None:
+ auth = KickscaleAuth(api_key="key-1", client_id="client-1")
+ assert set(auth.secret_values()) == {"key-1", "client-1"}
+
+
+class TestKickscalePageNumberPaginator:
+ @parameterized.expand(
+ [
+ ("full_page_keeps_going", 100, 100, True),
+ ("short_page_is_terminal", 100, 40, False),
+ ("empty_page_is_terminal", 100, 0, False),
+ ]
+ )
+ def test_termination(self, _name: str, page_size: int, row_count: int, expected_has_next: bool) -> None:
+ paginator = KickscalePageNumberPaginator(page_size=page_size)
+ response = Mock()
+ response.json.return_value = [{"id": str(i)} for i in range(row_count)]
+ data = [{"id": str(i)} for i in range(row_count)]
+
+ paginator.update_state(response, data=data)
+
+ assert paginator.has_next_page is expected_has_next
+
+ def test_page_param_advances_and_is_zero_based(self) -> None:
+ paginator = KickscalePageNumberPaginator(page_size=100)
+ request = Request(method="GET", url="https://api.kickscale.com/meetings")
+ paginator.init_request(request)
+ assert request.params["page"] == 0
+
+ paginator.update_state(Mock(), data=[{"id": "1"}] * 100)
+ paginator.update_request(request)
+ assert request.params["page"] == 1
+
+ def test_resume_state_round_trip(self) -> None:
+ paginator = KickscalePageNumberPaginator(page_size=100)
+ paginator.update_state(Mock(), data=[{"id": "1"}] * 100)
+ state = paginator.get_resume_state()
+ assert state == {"page": 1}
+
+ resumed = KickscalePageNumberPaginator(page_size=100)
+ resumed.set_resume_state(cast(dict[str, Any], state))
+ request = Request(method="GET", url="https://api.kickscale.com/meetings")
+ resumed.init_request(request)
+ assert request.params["page"] == 1
+
+
+ [
+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "2026-03-01T12:30:45Z"),
+ ("aware_datetime", datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC), "2026-03-01T12:30:45Z"),
+ ("passthrough_string", "1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z"),
+ ]
+)
+def test_format_kickscale_datetime(_name: str, value: Any, expected: str) -> None:
+ assert _format_kickscale_datetime(value) == expected
+
+
+class TestGetResource:
+ @pytest.mark.parametrize("endpoint", ["meetings", "calls"])
+ def test_incremental_resource(self, endpoint: str) -> None:
+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=True))
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ incremental = resource["endpoint"]["incremental"]
+ assert incremental["start_param"] == "startDate"
+ assert incremental["cursor_path"] == "date"
+
+ @pytest.mark.parametrize("endpoint", ["meetings", "calls"])
+ def test_full_refresh_resource(self, endpoint: str) -> None:
+ resource = cast(dict[str, Any], get_resource(endpoint, should_use_incremental_field=False))
+ assert resource["write_disposition"] == "replace"
+ assert "incremental" not in resource["endpoint"]
+
+ def test_requests_both_scopes_and_expand(self) -> None:
+ resource = cast(dict[str, Any], get_resource("meetings", should_use_incremental_field=False))
+ params = resource["endpoint"]["params"]
+ # `scopes` defaults to "external" only; "internal" must be requested explicitly or
+ # internal meetings silently drop out of every list response.
+ assert params["scopes"] == "internal,external"
+ assert params["expand"] == "user_client_augmentation,meeting_transcript"
+ assert params["sortingOrder"] == "ascending"
+
+
+def test_client_config_pins_host_and_blocks_redirects() -> None:
+ # A redirect off the Kickscale host would otherwise replay the api-key/client-id headers.
+ config = _client_config("key", "client")
+ assert config["allowed_hosts"] == []
+ assert config["allow_redirects"] is False
+
+
+ [
+ (200, True, None),
+ (403, False, "Check both values"),
+ (500, False, "unexpected status code"),
+ ]
+)
+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.kickscale.make_tracked_session")
+def test_validate_credentials_status_mapping(
+ status: int, expected_valid: bool, message_fragment: str | None, mock_session: MagicMock
+) -> None:
+ mock_session.return_value.get.return_value = Mock(status_code=status)
+
+ is_valid, message = validate_credentials("kickscale-key", "kickscale-client")
+
+ assert is_valid is expected_valid
+ if message_fragment is None:
+ assert message is None
+ else:
+ assert message is not None and message_fragment in message
+
+ call = mock_session.return_value.get.call_args
+ assert call.args[0] == "https://api.kickscale.com/meetings"
+ assert call.kwargs["headers"]["api-key"] == "kickscale-key"
+ assert call.kwargs["headers"]["client-id"] == "kickscale-client"
+ # The validation session must refuse redirects so a 3xx can't replay the credentials off-host.
+ assert mock_session.call_args.kwargs["allow_redirects"] is False
+
+
+def _make_http_response(body: list[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
+
+
+class TestKickscaleSourceResumeBehavior:
+ """End-to-end resume behaviour of ``kickscale_source`` via ``rest_api_resource``."""
+
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response]
+ ) -> tuple[MagicMock, list[dict[str, Any]]]:
+ 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 mock_session_cls:
+ mock_session = mock_session_cls.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ response = kickscale_source(
+ api_key="test-key",
+ client_id="test-client",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ list(cast(Iterable[Any], response.items()))
+ return mock_session, sent_params
+
+ @pytest.mark.parametrize("endpoint", ["meetings", "calls"])
+ def test_fresh_run_pages_until_short_page(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [
+ _make_http_response([{"id": f"m{i}"} for i in range(100)]),
+ _make_http_response([{"id": "m100"}]),
+ ]
+ _, sent_params = self._drive(endpoint, manager, responses)
+
+ pages_sent = [p.get("page") for p in sent_params]
+ assert pages_sent == [0, 1]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [KickscaleResumeConfig(page=1)]
+
+ def test_resume_seeds_paginator_with_saved_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = KickscaleResumeConfig(page=3)
+
+ responses = [_make_http_response([{"id": "m1"}])]
+ _, sent_params = self._drive("meetings", manager, responses)
+
+ assert [p.get("page") for p in sent_params] == [3]
+ manager.load_state.assert_called_once()
+
+ def test_terminal_single_page_does_not_save_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{"id": "only"}])]
+ self._drive("meetings", manager, responses)
+
+ manager.save_state.assert_not_called()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_make_http_response([{"id": "a"}])]
+ self._drive("meetings", manager, responses)
+
+ manager.load_state.assert_not_called()
+
+ @pytest.mark.parametrize("endpoint", ["meetings", "calls"])
+ def test_response_shape(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ responses = [_make_http_response([{"id": "1"}])]
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as mock_session_cls:
+ mock_session = mock_session_cls.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ response_iter = iter(responses)
+ mock_session.send.side_effect = lambda *_a, **_k: next(response_iter)
+
+ response = kickscale_source(
+ api_key="test-key",
+ client_id="test-client",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["date"]
+ assert response.chunk_size == 1000
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/tests/test_kickscale_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/tests/test_kickscale_source.py
new file mode 100644
index 000000000000..a5e327e3c42c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kickscale/tests/test_kickscale_source.py
@@ -0,0 +1,136 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kickscale import (
+ KickscaleSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.kickscale import KickscaleResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.settings import (
+ ENDPOINTS,
+ INCREMENTAL_LOOKBACK_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.source import KickscaleSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestKickscaleSource:
+ def setup_method(self) -> None:
+ self.source = KickscaleSource()
+ self.team_id = 123
+ self.config = KickscaleSourceConfig(api_key="kickscale-key", client_id="kickscale-client")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.KICKSCALE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Kickscale"
+ assert config.label == "Kickscale"
+ assert config.category == DataWarehouseSourceCategory.SALES
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/kickscale.png"
+ # The source ships visible — a truthy unreleasedSource hides it from every user.
+ assert not config.unreleasedSource
+
+ def test_fields_have_correct_secrecy(self) -> None:
+ config = self.source.get_source_config
+ fields = {f.name: f for f in config.fields}
+ assert set(fields) == {"api_key", "client_id"}
+
+ api_key_field = fields["api_key"]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ client_id_field = fields["client_id"]
+ assert isinstance(client_id_field, SourceFieldInputConfig)
+ assert client_id_field.type == SourceFieldInputConfigType.TEXT
+ assert client_id_field.secret is False
+ assert client_id_field.required is True
+
+ def test_get_schemas_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_incremental_semantics(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ for name in ENDPOINTS:
+ assert schemas[name].supports_incremental is True, name
+ assert [f["field"] for f in schemas[name].incremental_fields] == ["date"], name
+ assert schemas[name].default_incremental_lookback_seconds == INCREMENTAL_LOOKBACK_SECONDS, name
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["calls"])
+ assert [s.name for s in schemas] == ["calls"]
+
+ @pytest.mark.parametrize(
+ "observed_error,expect_match",
+ [
+ ("403 Client Error: Forbidden for url: https://api.kickscale.com/meetings", True),
+ ("401 Client Error: Unauthorized for url: https://api.kickscale.com/meetings", False),
+ ("500 Server Error: Internal Server Error for url: https://api.kickscale.com/meetings", False),
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures_only(self, observed_error: str, expect_match: bool) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable) is expect_match
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.source.validate_kickscale_credentials"
+ )
+ def test_validate_credentials_plumbs_both_headers(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+ assert self.source.validate_credentials(self.config, self.team_id) == (True, None)
+ assert mock_validate.call_args.args == ("kickscale-key", "kickscale-client")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert manager._data_class is KickscaleResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.source.kickscale_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_kickscale_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "meetings"
+ inputs.team_id = self.team_id
+ inputs.job_id = "job-1"
+ inputs.should_use_incremental_field = True
+ inputs.incremental_field = "date"
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_kickscale_source.call_args.kwargs
+ assert kwargs["api_key"] == "kickscale-key"
+ assert kwargs["client_id"] == "kickscale-client"
+ assert kwargs["endpoint"] == "meetings"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["incremental_field"] == "date"
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.kickscale.source.kickscale_source")
+ def test_source_for_pipeline_omits_watermark_when_not_incremental(
+ self, mock_kickscale_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "meetings"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_kickscale_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)