: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 the kapa.ai import source (#108635)
Tom Owers179476fd8eb0
diff --git a/frontend/public/services/kapa_ai.png b/frontend/public/services/kapa_ai.pngnew file mode 100644index 000000000000..eaed0539d659Binary files /dev/null and b/frontend/public/services/kapa_ai.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c14a5dbcc16e..b35d910a1fdf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -411,6 +411,7 @@ the row lists both.| k6_cloud | HTTP | requests | ✅ || kalshi | HTTP | requests (rest_source.RESTClient) | ✅ || kandji | HTTP | requests (rest_source.RESTClient) | ✅ |+| kapa_ai | HTTP | requests + `rest_source.RESTClient` | ✅ || katana | HTTP | requests | ✅ || kernel | HTTP | requests | ✅ || kickscale | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1157,7 +1158,6 @@ doesn't conflict with concurrent PRs.- kafka- kajabi- kameleoon-- kapa_ai- kaufland_marketplace- keka- kestradiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kapaai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kapaai.pyindex d398b4dc48e3..2e5eab1d137c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kapaai.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kapaai.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass KapaAISourceConfig(config.Config):- pass+ api_key: str+ project_id: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/canonical_descriptions.pynew file mode 100644index 000000000000..ce61ca122a7e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/canonical_descriptions.py@@ -0,0 +1,78 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "threads": {+ "description": "Conversations with nested question-answer pairs, feedback, tags, end user, and integration data.",+ "docs_url": "https://docs.kapa.ai/api/reference/query-v-1-projects-threads-list",+ "columns": {+ "id": "Unique conversation identifier.",+ "created_at": "Time the conversation started in UTC.",+ "last_activity_at": "Time of the most recent conversation activity, which can be null.",+ "question_answers": "Question-answer pairs included in the thread listing.",+ "has_more_question_answers": "Whether the conversation has question-answer pairs beyond those included in the listing.",+ },+ },+ "end_users": {+ "description": "People who interact with the project's assistant.",+ "docs_url": "https://docs.kapa.ai/api/reference/query-v-1-projects-end-users-list",+ "columns": {"id": "Unique end user identifier.", "created_at": "Time the end user record was created."},+ },+ "sources": {+ "description": "Knowledge sources connected to the project.",+ "docs_url": "https://docs.kapa.ai/api/reference/ingestion-v-1-projects-sources-list",+ "columns": {"id": "Unique knowledge source identifier.", "created_at": "Time the source was created."},+ },+ "source_groups": {+ "description": "Groups of knowledge sources, including nested groups.",+ "docs_url": "https://docs.kapa.ai/api/reference/ingestion-v-1-projects-source-groups-list",+ "columns": {"id": "Unique source group identifier.", "created_at": "Time the group was created."},+ },+ "integrations": {+ "description": "Deployment integrations configured for the project.",+ "docs_url": "https://docs.kapa.ai/api/reference/query-v-1-projects-integrations-list",+ "columns": {"id": "Unique integration identifier.", "created_at": "Time the integration was created."},+ },+ "activity": {+ "description": "Project activity snapshot with aggregate and per-integration query, feedback, user, and deflection statistics.",+ "docs_url": "https://docs.kapa.ai/api/reference/query-v-1-projects-activity-retrieve",+ "columns": {+ "project_id": "Project identifier attached to the activity snapshot.",+ "aggregate_statistics": "Activity totals for the project.",+ "statistics_by_integration": "Activity totals grouped by deployment integration.",+ },+ },+ "top_question_periods": {+ "description": "Completed weekly, monthly, or quarterly periods used to group frequently asked questions.",+ "docs_url": "https://docs.kapa.ai/api/reference/query-v-1-projects-top-questions-periods-list",+ "columns": {"id": "Unique period identifier.", "start_date": "Start date of the period in UTC."},+ },+ "coverage_gap_periods": {+ "description": "Completed periods used to group conversations with uncertain answers.",+ "docs_url": "https://docs.kapa.ai/api/reference/query-v-1-projects-coverage-gaps-periods-list",+ "columns": {"id": "Unique period identifier.", "start_date": "Start date of the period in UTC."},+ },+ "top_questions": {+ "description": "Question clusters for each completed period, with titles, summaries, counts, and recent conversations.",+ "docs_url": "https://docs.kapa.ai/api/reference/query-v-1-top-questions-periods-retrieve",+ "columns": {+ "id": "Unique cluster identifier.",+ "period_id": "Identifier of the parent analytics period.",+ "period_start_date": "Start date of the parent period in UTC.",+ "thread_count": "Total conversation count, including conversations outside the inline sample.",+ "threads": "At most 100 of the most recent conversations in the cluster.",+ },+ },+ "coverage_gaps": {+ "description": "Clusters of uncertain answers for each completed period, with suggestions for improving documentation.",+ "docs_url": "https://docs.kapa.ai/api/reference/query-v-1-coverage-gaps-periods-retrieve",+ "columns": {+ "id": "Unique cluster identifier.",+ "period_id": "Identifier of the parent analytics period.",+ "period_start_date": "Start date of the parent period in UTC.",+ "thread_count": "Total conversation count, including conversations outside the inline sample.",+ "threads": "At most 100 of the most recent conversations in the cluster.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/kapa_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/kapa_ai.pynew file mode 100644index 000000000000..77645e18e54e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/kapa_ai.py@@ -0,0 +1,152 @@+from collections.abc import Iterator+from typing import Any+from uuid import UUID++from requests.exceptions import HTTPError++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+ rest_api_resources,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+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.common.schema import schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.kapa_ai.settings import BASE_URL, ENDPOINTS++AUTH_ERRORS = {+ 401: "Your kapa.ai API key is invalid or expired. Create a new key and reconnect.",+ 403: "Your kapa.ai API key cannot access this data. Check the key's project access and permissions.",+ 404: "The kapa.ai project was not found. Check your project ID and the key's project access.",+}+++@frozen+class KapaResumeConfig:+ paginator_state: dict[str, Any] | None = None+++def get_resource(name: str, project_id: str, page_size: int = 100) -> EndpointResource:+ definition = schema_for_resource(ENDPOINTS, name)+ endpoint = definition.endpoint.copy()+ endpoint["path"] = str(endpoint["path"]).replace("{project_id}", str(UUID(project_id)))+ params = dict(endpoint.get("params") or {})+ if endpoint["paginator"] != "single_page":+ params["page_size"] = page_size+ endpoint["params"] = params+ resource: EndpointResource = {"name": name, "endpoint": endpoint, "write_disposition": "replace"}++ if definition.parent:+ parent = definition.parent+ params["period_id"] = {"type": "resolve", "resource": parent, "field": "id"}+ resource["include_from_parent"] = ["id", "start_date", "end_date", "interval"]++ def map_period(row: dict[str, Any]) -> dict[str, Any]:+ for key in ("id", "start_date", "end_date", "interval"):+ row[f"period_{key}"] = row.pop(f"_{parent}_{key}")+ return row++ resource["data_map"] = map_period+ elif name == "activity":+ resource["data_map"] = lambda row: {**row, "project_id": str(UUID(project_id))}+ return resource+++def build_resource(+ api_key: str,+ project_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ manager: ResumableSourceManager[KapaResumeConfig] | None = None,+ resume: KapaResumeConfig | None = None,+ page_size: int = 100,+) -> Resource:+ definition = schema_for_resource(ENDPOINTS, endpoint)+ resources: list[str | EndpointResource] = [get_resource(endpoint, project_id, page_size)]+ if definition.parent:+ resources.insert(0, get_resource(definition.parent, project_id, page_size))+ config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ "auth": {"type": "api_key", "name": "X-API-KEY", "api_key": api_key, "location": "header"},+ "headers": {"Accept": "application/json"},+ "allowed_hosts": ["api.kapa.ai"],+ "allow_redirects": False,+ "request_timeout": (10, 60),+ },+ "resources": resources,+ }++ def save_state(state: dict[str, Any] | None) -> None:+ if manager is not None:+ manager.save_state(KapaResumeConfig(paginator_state=state))++ factory = rest_api_resources if definition.parent else rest_api_resource+ result = factory(+ config,+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ resume_hook=save_state if manager else None,+ initial_paginator_state=resume.paginator_state if resume else None,+ )+ return result[-1] if isinstance(result, list) else result+++def validate_credentials(+ api_key: str, project_id: str, team_id: int, schema_name: str | None = None+) -> tuple[bool, str | None]:+ try:+ UUID(project_id)+ except ValueError:+ return False, "Enter a valid kapa.ai project ID in UUID format."+ if (+ not api_key+ or not api_key.isascii()+ or any(character.isspace() for character in api_key)+ or not api_key.isprintable()+ ):+ return False, "Enter a valid kapa.ai API key without whitespace or unsupported characters."+ if schema_name is not None and schema_name not in ENDPOINTS:+ return False, "Unknown kapa.ai table. Refresh the table list and try again."+ try:+ for _ in build_resource(api_key, project_id, schema_name or "threads", team_id, "", page_size=1):+ break+ except HTTPError as error:+ status = error.response.status_code if error.response is not None else None+ if status is not None and status in AUTH_ERRORS:+ return False, AUTH_ERRORS[status]+ raise+ return True, None+++def kapa_ai_source(+ api_key: str,+ project_id: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[KapaResumeConfig],+) -> SourceResponse:+ definition = schema_for_resource(ENDPOINTS, endpoint)++ def get_rows() -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ resource = build_resource(api_key, project_id, endpoint, team_id, job_id, resumable_source_manager, resume)+ yield from resource+ resumable_source_manager.clear_state()++ return SourceResponse(+ name=endpoint,+ items=get_rows,+ primary_keys=list(definition.primary_keys),+ partition_keys=[definition.partition_key] if definition.partition_key else None,+ partition_mode="datetime" if definition.partition_key else None,+ partition_format="month" if definition.partition_key else None,+ sort_mode=None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/settings.pynew file mode 100644index 000000000000..2668a4dcc0ee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/settings.py@@ -0,0 +1,98 @@+from dataclasses import field++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.kapa.ai"+THREAD_INCLUDES = "feedback,status_tag,custom_tags,interaction_tags,end_user,integration"+++@frozen+class KapaEndpoint:+ endpoint: Endpoint+ primary_keys: tuple[str, ...] = ("id",)+ partition_key: str | None = "created_at"+ parent: str | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++CURSOR_ENDPOINT: Endpoint = {+ "paginator": {"type": "cursor", "cursor_path": "next_cursor", "cursor_param": "cursor"},+ "data_selector_required": True,+}+PAGE_ENDPOINT: Endpoint = {+ "paginator": {"type": "json_response", "next_url_path": "next"},+ "data_selector": "results",+ "data_selector_required": True,+}++# Enable updated_since only after verifying server-side filtering against a real account.+ENDPOINTS: dict[str, KapaEndpoint] = {+ "threads": KapaEndpoint(+ endpoint={+ **CURSOR_ENDPOINT,+ "path": "/query/v1/projects/{project_id}/threads/",+ "data_selector": "results",+ "params": {"include": THREAD_INCLUDES, "sort": "asc"},+ },+ ),+ "end_users": KapaEndpoint(endpoint={**PAGE_ENDPOINT, "path": "/query/v1/projects/{project_id}/end-users/"}),+ "sources": KapaEndpoint(endpoint={**PAGE_ENDPOINT, "path": "/ingestion/v1/projects/{project_id}/sources/"}),+ "source_groups": KapaEndpoint(+ endpoint={**PAGE_ENDPOINT, "path": "/ingestion/v1/projects/{project_id}/source-groups/"}+ ),+ "integrations": KapaEndpoint(+ endpoint={+ "path": "/query/v1/projects/{project_id}/integrations/",+ "paginator": "single_page",+ "data_selector": "$",+ },+ ),+ "activity": KapaEndpoint(+ endpoint={+ "path": "/query/v1/projects/{project_id}/activity/",+ "paginator": "single_page",+ "data_selector": "$",+ },+ primary_keys=("project_id",),+ partition_key=None,+ ),+ "top_question_periods": KapaEndpoint(+ endpoint={+ **CURSOR_ENDPOINT,+ "path": "/query/v1/projects/{project_id}/top-questions/periods/",+ "data_selector": "periods",+ },+ partition_key="start_date",+ ),+ "coverage_gap_periods": KapaEndpoint(+ endpoint={+ **CURSOR_ENDPOINT,+ "path": "/query/v1/projects/{project_id}/coverage-gaps/periods/",+ "data_selector": "periods",+ },+ partition_key="start_date",+ ),+ "top_questions": KapaEndpoint(+ endpoint={+ **CURSOR_ENDPOINT,+ "path": "/query/v1/top-questions/periods/{period_id}/",+ "data_selector": "clusters",+ },+ primary_keys=("period_id", "id"),+ partition_key="period_start_date",+ parent="top_question_periods",+ ),+ "coverage_gaps": KapaEndpoint(+ endpoint={+ **CURSOR_ENDPOINT,+ "path": "/query/v1/coverage-gaps/periods/{period_id}/",+ "data_selector": "clusters",+ },+ primary_keys=("period_id", "id"),+ partition_key="period_start_date",+ parent="coverage_gap_periods",+ ),+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/source.pyindex 2206f7a4ef63..b57a130ecb15 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/source.py@@ -1,26 +1,123 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+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, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kapaai import KapaAISourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kapa_ai.kapa_ai import (+ AUTH_ERRORS,+ KapaResumeConfig,+ kapa_ai_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kapa_ai.settings import ENDPOINTSfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class KapaAISource(SimpleSource[KapaAISourceConfig]):+class KapaAISource(ResumableSource[KapaAISourceConfig, KapaResumeConfig]):+ lists_tables_without_credentials = True+ api_docs_url = "https://docs.kapa.ai/api/reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.KAPAAI+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {f"{status} Client Error": message for status, message in AUTH_ERRORS.items()}++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.kapa_ai.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: KapaAISourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS, {name: endpoint.incremental_fields for name, endpoint in ENDPOINTS.items()}, names+ )++ def validate_credentials(+ self,+ config: KapaAISourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(config.api_key, config.project_id, team_id, schema_name)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KapaResumeConfig]:+ return ResumableSourceManager(inputs, KapaResumeConfig)++ def source_for_pipeline(+ self,+ config: KapaAISourceConfig,+ resumable_source_manager: ResumableSourceManager[KapaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return kapa_ai_source(+ api_key=config.api_key,+ project_id=config.project_id,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.KAPAAI,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="kapa.ai",+ docsUrl="https://posthog.com/docs/cdp/sources/kapa-ai",iconPath="/static/services/kapa_ai.png",keywords=["ai assistant", "docs", "support", "conversations"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ caption="Create an API key in kapa.ai under Configuration > API Keys. Find your project ID under Settings > Projects.",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ placeholder="",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ secret=True,+ ),+ SourceFieldInputConfig(+ name="project_id",+ label="Project ID",+ placeholder="",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ secret=False,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/tests/test_kapa_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/tests/test_kapa_ai.pynew file mode 100644index 000000000000..f6429f30f76e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/tests/test_kapa_ai.py@@ -0,0 +1,266 @@+import json+from collections.abc import Iterable, Iterator+from http import HTTPStatus+from typing import Any, cast+from urllib.parse import parse_qs, urlsplit++import pytest+from unittest.mock import MagicMock, patch++from requests import Response+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import RESTClient+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.kapa_ai.kapa_ai import (+ KapaResumeConfig,+ kapa_ai_source,+ validate_credentials,+)++PROJECT_ID = "00000000-0000-4000-8000-000000000001"+API_KEY = "test-kapa-key"+BASE_URL = "https://api.kapa.ai"+++def response(body: object, status: int = 200) -> Response:+ result = Response()+ result.status_code = status+ result.reason = HTTPStatus(status).phrase+ result.url = BASE_URL+ result._content = json.dumps(body).encode()+ result.headers["Content-Type"] = "application/json"+ return result+++def http() -> Iterator[MagicMock]:+ with patch("requests.sessions.Session.send") as send:+ yield send+++def manager() -> MagicMock:+ result = MagicMock(spec=ResumableSourceManager)+ result.can_resume.return_value = False+ return result+++def source(endpoint: str, manager: MagicMock) -> SourceResponse:+ return kapa_ai_source(API_KEY, PROJECT_ID, endpoint, 1, "test-job", manager)+++def pages(result: SourceResponse) -> list[list[dict[str, Any]]]:+ return list(cast(Iterable[list[dict[str, Any]]], result.items()))++[email protected]("terminal_rows", [[], [{"id": "thread-2"}]])+def test_thread_pagination_preserves_nested_data_and_checkpoints_after_yield(+ http: MagicMock, manager: MagicMock, terminal_rows: list[dict[str, str]]+) -> None:+ thread = {"id": "thread-1", "question_answers": [{"question": "How do test widgets work?", "feedback": []}]}+ http.side_effect = [+ response({"results": [thread], "next_cursor": "next-page"}),+ response({"results": terminal_rows, "next_cursor": None}),+ ]+ rows = iter(cast(Iterable[list[dict[str, Any]]], source("threads", manager).items()))+ assert next(rows) == [thread]+ manager.save_state.assert_not_called()+ assert list(rows) == ([terminal_rows] if terminal_rows else [])+ assert manager.save_state.call_args_list[0].args[0].paginator_state == {"cursor": "next-page"}+ manager.clear_state.assert_called_once()+ first, second = [call.args[0] for call in http.call_args_list]+ assert first.headers["X-API-KEY"] == API_KEY+ params = parse_qs(urlsplit(first.url).query)+ assert params["include"] == ["feedback,status_tag,custom_tags,interaction_tags,end_user,integration"]+ assert params["sort"] == ["asc"]+ assert params["page_size"] == ["100"]+ assert "updated_since" not in params+ assert parse_qs(urlsplit(second.url).query)["cursor"] == ["next-page"]+ assert urlsplit(first.url).path == f"/query/v1/projects/{PROJECT_ID}/threads/"+++ "endpoint,path",+ [+ ("end_users", "query/v1/projects/{}/end-users/"),+ ("sources", "ingestion/v1/projects/{}/sources/"),+ ("source_groups", "ingestion/v1/projects/{}/source-groups/"),+ ],+)+def test_page_links_are_followed_and_resume_at_the_saved_url(+ http: MagicMock, manager: MagicMock, endpoint: str, path: str+) -> None:+ next_url = f"{BASE_URL}/{path.format(PROJECT_ID)}?page=2&page_size=100"+ http.side_effect = [+ response({"count": 2, "results": [{"id": "first"}], "next": next_url}),+ response({"count": 2, "results": [{"id": "last"}], "next": None}),+ ]+ assert pages(source(endpoint, manager)) == [[{"id": "first"}], [{"id": "last"}]]+ saved = manager.save_state.call_args_list[0].args[0]+ manager.can_resume.return_value = True+ manager.load_state.return_value = saved+ http.reset_mock(side_effect=True)+ http.return_value = response({"count": 2, "results": [{"id": "last"}], "next": None})+ assert pages(source(endpoint, manager)) == [[{"id": "last"}]]+ assert http.call_count == 1+ assert http.call_args.args[0].url == next_url+++def test_cursor_resume_clears_state_after_completion(http: MagicMock, manager: MagicMock) -> None:+ manager.can_resume.return_value = True+ manager.load_state.return_value = KapaResumeConfig(paginator_state={"cursor": "saved-cursor"})+ http.return_value = response({"results": [{"id": "last"}], "next_cursor": None})+ assert pages(source("threads", manager)) == [[{"id": "last"}]]+ assert parse_qs(urlsplit(http.call_args.args[0].url).query)["cursor"] == ["saved-cursor"]+ manager.clear_state.assert_called_once()+++ "endpoint,body,expected",+ [+ ("integrations", [{"id": "integration-1"}], [{"id": "integration-1"}]),+ ("integrations", [], []),+ (+ "activity",+ {"aggregate_statistics": {"total_query_count": 4}, "statistics_by_integration": []},+ [+ {+ "aggregate_statistics": {"total_query_count": 4},+ "statistics_by_integration": [],+ "project_id": PROJECT_ID,+ }+ ],+ ),+ ],+)+def test_unpaginated_responses_keep_their_shape(+ http: MagicMock, manager: MagicMock, endpoint: str, body: object, expected: list[dict[str, Any]]+) -> None:+ http.return_value = response(body)+ result = source(endpoint, manager)+ assert pages(result) == ([expected] if expected else [])+ assert http.call_count == 1+ assert not urlsplit(http.call_args.args[0].url).query+ assert all(key in row for row in expected for key in result.primary_keys or [])++[email protected]("endpoint,api_path", [("top_questions", "top-questions"), ("coverage_gaps", "coverage-gaps")])+def test_period_fanout_paginates_both_levels_and_resumes_children(+ http: MagicMock, manager: MagicMock, endpoint: str, api_path: str+) -> None:+ period1 = {"id": "period-1", "start_date": "2025-01-01", "end_date": "2025-02-01", "interval": "monthly"}+ period2 = {**period1, "id": "period-2", "start_date": "2025-02-01"}+ parent_page1 = response({"periods": [period1], "next_cursor": "period-page-2"})+ parent_page2 = response({"periods": [period2], "next_cursor": None})+ http.side_effect = [+ parent_page1,+ response(+ {"clusters": [{"id": "cluster-1", "thread_count": 123, "threads": []}], "next_cursor": "cluster-page-2"}+ ),+ response({"clusters": [{"id": "cluster-2"}], "next_cursor": None}),+ parent_page2,+ response({"clusters": [{"id": "cluster-1"}], "next_cursor": None}),+ ]+ result = source(endpoint, manager)+ rows = [row for page in pages(result) for row in page]+ assert [(row["period_id"], row["id"]) for row in rows] == [+ ("period-1", "cluster-1"),+ ("period-1", "cluster-2"),+ ("period-2", "cluster-1"),+ ]+ assert rows[0]["period_start_date"] == "2025-01-01"+ assert rows[0]["thread_count"] == 123+ assert rows[0]["threads"] == []+ assert result.primary_keys == ["period_id", "id"]+ assert result.partition_keys == ["period_start_date"]+ urls = [call.args[0].url for call in http.call_args_list]+ assert urlsplit(urls[1]).path == f"/query/v1/{api_path}/periods/period-1/"+ assert parse_qs(urlsplit(urls[2]).query)["cursor"] == ["cluster-page-2"]+ assert parse_qs(urlsplit(urls[3]).query)["cursor"] == ["period-page-2"]+ manager.can_resume.return_value = True+ manager.load_state.return_value = manager.save_state.call_args_list[0].args[0]+ http.reset_mock(side_effect=True)+ http.side_effect = [+ parent_page1,+ response({"clusters": [{"id": "cluster-2"}], "next_cursor": None}),+ parent_page2,+ response({"clusters": [], "next_cursor": None}),+ ]+ assert [row["id"] for page in pages(source(endpoint, manager)) for row in page] == ["cluster-2"]+ assert parse_qs(urlsplit(http.call_args_list[1].args[0].url).query)["cursor"] == ["cluster-page-2"]+++ "status,schema,valid,message",+ [+ (200, None, True, None),+ (401, None, False, "Your kapa.ai API key is invalid or expired. Create a new key and reconnect."),+ (+ 403,+ None,+ False,+ "Your kapa.ai API key cannot access this data. Check the key's project access and permissions.",+ ),+ (+ 403,+ "sources",+ False,+ "Your kapa.ai API key cannot access this data. Check the key's project access and permissions.",+ ),+ (404, None, False, "The kapa.ai project was not found. Check your project ID and the key's project access."),+ ],+)+def test_credential_probe_status_mapping(+ http: MagicMock, status: int, schema: str | None, valid: bool, message: str | None+) -> None:+ http.return_value = response({"results": [], "next_cursor": None}, status)+ assert validate_credentials(API_KEY, PROJECT_ID, 1, schema) == (valid, message)+ assert http.call_count == 1+ assert parse_qs(urlsplit(http.call_args.args[0].url).query)["page_size"] == ["1"]+++ "project_id,key,schema,message",+ [+ ("../threads", API_KEY, None, "Enter a valid kapa.ai project ID in UUID format."),+ (PROJECT_ID, "bad\nkey", None, "Enter a valid kapa.ai API key without whitespace or unsupported characters."),+ (PROJECT_ID, "", None, "Enter a valid kapa.ai API key without whitespace or unsupported characters."),+ (PROJECT_ID, API_KEY, "missing", "Unknown kapa.ai table. Refresh the table list and try again."),+ ],+)+def test_invalid_configuration_never_sends_a_request(+ http: MagicMock, project_id: str, key: str, schema: str | None, message: str+) -> None:+ assert validate_credentials(key, project_id, 1, schema) == (False, message)+ http.assert_not_called()++[email protected]("status", [429, 500, 503])+def test_transient_statuses_are_retried_by_shared_client(http: MagicMock, manager: MagicMock, status: int) -> None:+ http.side_effect = [response({}, status), response({"results": [{"id": "thread-1"}], "next_cursor": None})]+ with patch.object(RESTClient._send_request.retry, "wait", return_value=0): # type: ignore[attr-defined]+ assert pages(source("threads", manager)) == [[{"id": "thread-1"}]]+ assert http.call_count == 2+++def test_unexpected_probe_error_is_not_reported_as_bad_credentials(http: MagicMock) -> None:+ http.return_value = response({}, 400)+ with pytest.raises(HTTPError):+ validate_credentials(API_KEY, PROJECT_ID, 1)+++def test_missing_response_collection_fails_instead_of_erasing_the_table(http: MagicMock, manager: MagicMock) -> None:+ http.return_value = response({"unexpected": []})+ with pytest.raises(ValueError, match="results"):+ pages(source("threads", manager))+ manager.clear_state.assert_not_called()++[email protected]("next_url", ["https://example.com/collect", "http://api.kapa.ai/query/v1/threads/"])+def test_pagination_cannot_send_the_key_to_another_origin(http: MagicMock, manager: MagicMock, next_url: str) -> None:+ http.return_value = response({"results": [{"id": "user-1"}], "next": next_url})+ with pytest.raises(ValueError, match="Refusing to send request"):+ pages(source("end_users", manager))+ assert http.call_count == 1diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/tests/test_kapa_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/tests/test_kapa_ai_source.pynew file mode 100644index 000000000000..dc40f6ab190b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kapa_ai/tests/test_kapa_ai_source.py@@ -0,0 +1,65 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import error_message_matches+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 UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kapaai import KapaAISourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kapa_ai.source import KapaAISource++[email protected]("status,reason", [(401, "Unauthorized"), (403, "Forbidden")])+def test_pipeline_auth_failures_match_terminal_errors(status: int, reason: str) -> None:+ source = KapaAISource()+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ inputs = MagicMock(spec=SourceInputs, schema_name="threads", team_id=1, job_id="test-job")+ config = KapaAISourceConfig(api_key="test-key", project_id="00000000-0000-4000-8000-000000000001")+ response = Response()+ response.status_code = status+ response.reason = reason+ response.url = "https://api.kapa.ai/query/v1/projects/00000000-0000-4000-8000-000000000001/threads/"+ response._content = b"{}"+ with patch("requests.sessions.Session.send", return_value=response) as send:+ with pytest.raises(HTTPError) as error:+ list(cast(Iterable[Any], source.source_for_pipeline(config, manager, inputs).items()))+ assert send.call_count == 1+ assert error_message_matches(str(error.value), source.get_non_retryable_errors())+++def test_unknown_table_is_rejected_before_fetching() -> None:+ config = KapaAISourceConfig(api_key="test-key", project_id="00000000-0000-4000-8000-000000000001")+ inputs = MagicMock(spec=SourceInputs, schema_name="missing", team_id=1, job_id="test-job")+ with pytest.raises(UnknownResourceError, match="missing"):+ KapaAISource().source_for_pipeline(config, MagicMock(spec=ResumableSourceManager), inputs)+++def test_full_refresh_ignores_a_stale_watermark() -> None:+ config = KapaAISourceConfig(api_key="test-key", project_id="00000000-0000-4000-8000-000000000001")+ inputs = MagicMock(+ spec=SourceInputs,+ schema_name="threads",+ team_id=1,+ job_id="test-job",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2025-01-01T00:00:00Z",+ )+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ response = Response()+ response.status_code = 200+ response._content = json.dumps(+ {"results": [{"id": "old-thread", "last_activity_at": None}], "next_cursor": None}+ ).encode()+ with patch("requests.sessions.Session.send", return_value=response) as send:+ result = KapaAISource().source_for_pipeline(config, manager, inputs)+ assert list(cast(Iterable[Any], result.items())) == [[{"id": "old-thread", "last_activity_at": None}]]+ assert "updated_since" not in send.call_args.args[0].urldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.pyindex dbb182bc9b6f..349df8271573 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py@@ -65,7 +65,6 @@ SOURCES_WITHOUT_AN_ICON_FILE = {"Hatchet","Hetzner","HeyGen",- "KapaAI","Kernel","Linode","Maxio",