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): implement klaus import source (#71241)

Tom Owers93c522aba9f8
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index e4a33439d10f..175fb08724d0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -282,6 +282,7 @@ the row lists both.
| kandji | HTTP | requests (rest_source.RESTClient) | ✅ |
| katana | HTTP | requests | ✅ |
| kernel | HTTP | requests | ✅ |
+| klaus | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
| koyeb | HTTP | requests | ✅ |
| kong_konnect | HTTP | requests | ✅ |
@@ -755,7 +756,6 @@ doesn't conflict with concurrent PRs.
- kisi
- kissmetrics
- klarna
-- klaus
- knock
- koyeb
- kyve
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 04625240c991..eca85df6896c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2334,7 +2334,8 @@ class KlarnaSourceConfig(config.Config):
@config.config
class KlausSourceConfig(config.Config):
- pass
+ subdomain: str
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/canonical_descriptions.py
new file mode 100644
index 000000000000..6383c395fc71
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/canonical_descriptions.py
@@ -0,0 +1,160 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://pub.klausapp.com/?urls.primaryName=Public+Export+API"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "reviews": {
+ "description": "Reviewed conversations with their manual reviews and comments, one row per conversation.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "externalId": "Identifier of the conversation in the connected helpdesk (e.g. the Zendesk Support ticket id).",
+ "url": "Link to the conversation in Zendesk QA.",
+ "externalUrl": "Link to the conversation in the connected helpdesk.",
+ "reviews": "Manual reviews given on the conversation, including reviewer, reviewee, score, and category ratings.",
+ "comments": "Conversation-level comments left by reviewers.",
+ "workspaceId": "Identifier of the Zendesk QA workspace the conversation belongs to.",
+ "workspaceName": "Name of the Zendesk QA workspace the conversation belongs to.",
+ "sourceType": "Type of the helpdesk connection the conversation came from.",
+ "createdAtISO": "When the conversation was created, in ISO 8601 format.",
+ "lastUpdatedISO": "When the conversation was last updated, in ISO 8601 format.",
+ "externalFields": "Custom fields carried over from the connected helpdesk.",
+ },
+ },
+ "autoqa_reviews": {
+ "description": "AutoQA (automatic quality assurance) reviews, one row per automatically reviewed conversation.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "autoqaReviewId": "Unique identifier of the AutoQA review.",
+ "accountId": "Identifier of the Zendesk QA account.",
+ "workspaceId": "Identifier of the workspace the review belongs to.",
+ "workspaceName": "Name of the workspace the review belongs to.",
+ "connectionId": "Identifier of the helpdesk connection the conversation came from.",
+ "externalTicketId": "Identifier of the conversation in the connected helpdesk.",
+ "conversationCreatedAt": "When the reviewed conversation was created.",
+ "createdAt": "When the AutoQA review was created.",
+ "updatedAt": "When the AutoQA review was last updated.",
+ "isBot": "Whether the reviewee is a bot.",
+ "revieweeExternalId": "Identifier of the reviewed agent in the connected helpdesk.",
+ "revieweeName": "Name of the reviewed agent.",
+ "revieweeEmail": "Email of the reviewed agent.",
+ "conversationChannel": "Channel the conversation took place on.",
+ "language": "Detected language of the conversation.",
+ },
+ },
+ "autoqa_ratings": {
+ "description": "Per-category AutoQA rating rows, one row per rated category per AutoQA review.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "autoqaRatingId": "Unique identifier of the AutoQA rating.",
+ "autoqaReviewId": "Identifier of the AutoQA review the rating belongs to.",
+ "ratingCategoryId": "Identifier of the rating category.",
+ "ratingCategoryName": "Name of the rating category.",
+ "autoqaCategoryType": "Type of the AutoQA category (e.g. grammar, tone, solution).",
+ "scorecardId": "Identifier of the scorecard the category belongs to.",
+ "scorecardName": "Name of the scorecard the category belongs to.",
+ "score": "Score given for the category.",
+ "weight": "Weight of the category in the overall score.",
+ "isCritical": "Whether the category is critical for the review.",
+ "rootCauses": "Root causes attached to the rating.",
+ "conversationCreatedAt": "When the rated conversation was created.",
+ "createdAt": "When the rating was created.",
+ "updatedAt": "When the rating was last updated.",
+ },
+ },
+ "csat": {
+ "description": "CSAT (customer satisfaction) survey responses on tickets.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "externalTicketId": "Identifier of the surveyed ticket in the connected helpdesk.",
+ "ticketCreatedAt": "When the surveyed ticket was created.",
+ "csatCreatedAt": "When the CSAT survey was created.",
+ "csatAnsweredAt": "When the customer answered the CSAT survey.",
+ "csatScore": "Normalized CSAT score.",
+ "csatRawScore": "Raw score as answered by the customer.",
+ "csatComment": "Free-text comment left by the customer.",
+ "csatReason": "Reason the customer selected for the score.",
+ "csatDrivers": "Predicted drivers behind the CSAT score.",
+ "agentName": "Name of the agent who handled the ticket.",
+ "agentEmail": "Email of the agent who handled the ticket.",
+ "conversationChannel": "Channel the conversation took place on.",
+ "helpdeskTags": "Tags on the ticket in the connected helpdesk.",
+ },
+ },
+ "users": {
+ "description": "Users in the Zendesk QA account.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the user.",
+ "name": "Name of the user.",
+ "email": "Email of the user.",
+ },
+ },
+ "workspaces": {
+ "description": "Workspaces in the Zendesk QA account.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the workspace.",
+ "name": "Name of the workspace.",
+ },
+ },
+ "quizzes": {
+ "description": "Quizzes created in the account, with participation statistics.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier of the quiz.",
+ "name": "Name of the quiz.",
+ "status": "Publication status of the quiz.",
+ "authorId": "Identifier of the user who created the quiz.",
+ "publishedDate": "When the quiz was published.",
+ "numberOfParticipants": "Number of users who responded to the quiz.",
+ "averageScorePercentage": "Average score across responses, as a percentage.",
+ "workspaceIds": "Workspaces the quiz is available in.",
+ },
+ },
+ "scorecards": {
+ "description": "Scorecards configured in each workspace, with their rating categories and groups.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "workspace_id": "Identifier of the workspace the scorecard belongs to.",
+ "id": "Unique identifier of the scorecard.",
+ "name": "Name of the scorecard.",
+ "categories": "Rating categories on the scorecard.",
+ "groups": "Category groups on the scorecard.",
+ "createdAt": "When the scorecard was created.",
+ "updatedAt": "When the scorecard was last updated.",
+ },
+ },
+ "disputes": {
+ "description": "Disputes raised against reviews in each workspace.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "workspace_id": "Identifier of the workspace the dispute belongs to.",
+ "disputeId": "Unique identifier of the dispute.",
+ "reviewId": "Identifier of the disputed review.",
+ "conversationId": "Identifier of the conversation the disputed review is on.",
+ "type": "Type of the dispute.",
+ "status": "Current status of the dispute.",
+ "createdBy": "User who raised the dispute.",
+ "assignee": "User the dispute is assigned to.",
+ "createdAt": "When the dispute was raised.",
+ "resolvedAt": "When the dispute was resolved.",
+ "resolutionTime": "Time taken to resolve the dispute.",
+ },
+ },
+ "calibration_sessions": {
+ "description": "Calibration sessions in each workspace, used to align reviewers on grading.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "workspace_id": "Identifier of the workspace the session belongs to.",
+ "id": "Unique identifier of the calibration session.",
+ "title": "Title of the calibration session.",
+ "createdBy": "Identifier of the user who created the session.",
+ "createdAt": "When the session was created.",
+ "updatedAt": "When the session was last updated.",
+ "dueAt": "When the session is due.",
+ "conversations": "Conversations included in the session.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/klaus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/klaus.py
new file mode 100644
index 000000000000..ac1593293c21
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/klaus.py
@@ -0,0 +1,395 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+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.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.settings import (
+ KLAUS_ENDPOINTS,
+ KlausEndpointConfig,
+)
+
+REQUEST_TIMEOUT = 60
+# The public API is aggressively rate limited (on the order of one request per
+# minute), so throttled requests are the norm mid-sync, not the exception: honor
+# Retry-After and keep the retry budget generous.
+MAX_RETRY_ATTEMPTS = 8
+MAX_RETRY_WAIT_SECONDS = 300.0
+# Klaus was founded in 2018; endpoints with a required fromDate get this floor on
+# full refresh / first sync so the window covers all history.
+DEFAULT_FROM_DATE = datetime(2015, 1, 1, tzinfo=UTC)
+# fromDate's inclusive/exclusive boundary behavior isn't documented, so re-read a
+# small window behind the watermark; merge dedupes the overlap on the primary key.
+INCREMENTAL_OVERLAP = timedelta(hours=1)
+
+_SUBDOMAIN_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")
+
+
+class KlausRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class KlausResumeConfig:
+ # Next page number to request, in the server's own page indexing. None means
+ # "start the stream at its first page" — used when the fan-out bookmark advances
+ # to a workspace whose first page index isn't known until its response arrives.
+ next_page: int | None = None
+ # The workspace currently being processed for fan-out endpoints. A stable
+ # workspace-ID bookmark (not a positional index) so workspaces added/removed
+ # between a crash and the retry can't resume us into the wrong workspace.
+ workspace_id: str | None = None
+
+
+def _normalize_subdomain(subdomain: str) -> str:
+ """Reduce whatever the user pasted (bare subdomain, full host, or URL) to the subdomain."""
+ value = subdomain.strip().lower()
+ value = value.removeprefix("https://").removeprefix("http://")
+ value = value.split("/")[0]
+ if value.endswith(".zendesk.com"):
+ value = value[: -len(".zendesk.com")]
+ return value
+
+
+def get_base_url(subdomain: str) -> str:
+ """Build https://{subdomain}.zendesk.com/qa, rejecting anything that could escape the host.
+
+ The strict character allow-list pins the request host under zendesk.com — a value
+ with dots or slashes could otherwise splice a different host into the URL and
+ receive the bearer token.
+ """
+ value = _normalize_subdomain(subdomain)
+ if not _SUBDOMAIN_RE.match(value):
+ raise ValueError(
+ "Zendesk QA subdomain must contain only letters, numbers, and hyphens (e.g. 'yourcompany' for yourcompany.zendesk.com)"
+ )
+ return f"https://{value}.zendesk.com/qa"
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ value = response.headers.get("Retry-After")
+ if value is None:
+ return None
+ try:
+ return max(float(value), 0.0)
+ except ValueError:
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ exception = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exception, KlausRetryableError) and exception.retry_after is not None:
+ return min(exception.retry_after + 1.0, MAX_RETRY_WAIT_SECONDS)
+ return wait_exponential_jitter(initial=10, max=MAX_RETRY_WAIT_SECONDS)(retry_state)
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ KlausRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=_retry_wait,
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise KlausRetryableError(
+ f"Zendesk QA API error (retryable): status={response.status_code}, url={url}",
+ retry_after=_parse_retry_after(response),
+ )
+
+ # The session never follows redirects (host pinning); a 3xx from a valid
+ # account is never expected and almost always means the subdomain is wrong.
+ if response.is_redirect:
+ raise Exception("Zendesk QA redirected the request, which usually means the configured subdomain is incorrect")
+
+ if not response.ok:
+ logger.error(f"Zendesk QA API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _coerce_datetime(value: Any) -> datetime | None:
+ if isinstance(value, datetime):
+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+ return None
+
+
+def _format_datetime(value: datetime) -> str:
+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _build_params(
+ config: KlausEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+
+ from_value: datetime | None = None
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ from_value = _coerce_datetime(db_incremental_field_last_value)
+ if from_value is not None:
+ from_value -= INCREMENTAL_OVERLAP
+
+ if from_value is None and config.requires_from_date:
+ from_value = DEFAULT_FROM_DATE
+
+ if from_value is not None:
+ params["fromDate"] = _format_datetime(from_value)
+
+ return params
+
+
+def _iter_endpoint_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ url: str,
+ params: dict[str, Any],
+ config: KlausEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[KlausResumeConfig],
+ resume_page: int | None,
+ workspace_id: str | None,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ """Page through one endpoint (or one workspace of a fan-out endpoint), yielding row batches.
+
+ The docs don't say whether page numbering starts at 0 or 1, so the first request
+ omits `page` and later requests derive the next index from the response's
+ pagination echo — correct for either base. proto3 JSON omits zero-valued fields,
+ which is why a missing `pagination.page` reads as 0 (a 0-indexed first page).
+ """
+ next_page: int | None = resume_page
+ last_page_echo: int | None = None
+
+ while True:
+ request_params = dict(params)
+ if config.paginated:
+ request_params["pageSize"] = config.page_size
+ if next_page is not None:
+ request_params["page"] = next_page
+
+ data = _fetch_page(session, url, request_params, headers, logger)
+ items = data.get(config.data_selector) or []
+ if not items:
+ return
+
+ if workspace_id is not None:
+ items = [{**item, "workspace_id": workspace_id} for item in items]
+
+ if not config.paginated:
+ yield items
+ return
+
+ pagination = data.get("pagination") or {}
+ current_page = int(pagination.get("page") or 0)
+ effective_page_size = int(pagination.get("pageSize") or config.page_size)
+
+ # Fail loudly instead of looping forever if the server stops advancing the
+ # page echo (e.g. it silently ignores the page param).
+ if last_page_echo is not None and current_page == last_page_echo:
+ raise Exception(f"Zendesk QA pagination did not advance (page echo stuck at {current_page}) for {url}")
+ last_page_echo = current_page
+
+ has_more = len(items) >= max(effective_page_size, 1)
+ yield items
+
+ if not has_more:
+ return
+
+ next_page = current_page + 1
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields
+ # the last page rather than skipping it — merge dedupes on the primary key.
+ resumable_source_manager.save_state(KlausResumeConfig(next_page=next_page, workspace_id=workspace_id))
+
+
+def _get_workspace_ids(
+ session: requests.Session,
+ headers: dict[str, str],
+ base_url: str,
+ logger: FilteringBoundLogger,
+) -> list[str]:
+ data = _fetch_page(session, f"{base_url}/api/export/workspaces", {}, headers, logger)
+ return [str(workspace["id"]) for workspace in data.get("workspaces") or []]
+
+
+def _iter_fanout_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ base_url: str,
+ params: dict[str, Any],
+ config: KlausEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[KlausResumeConfig],
+ resume: KlausResumeConfig | None,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ workspace_ids = _get_workspace_ids(session, headers, base_url, logger)
+
+ # Resolve the saved workspace bookmark to the slice still to process. If the
+ # bookmarked workspace no longer exists, start over from the first one — merge
+ # dedupes the re-pulled rows on the primary key.
+ remaining = workspace_ids
+ resume_page: int | None = None
+ if resume is not None and resume.workspace_id is not None and resume.workspace_id in workspace_ids:
+ remaining = workspace_ids[workspace_ids.index(resume.workspace_id) :]
+ resume_page = resume.next_page
+ logger.debug(f"Zendesk QA: resuming {config.name} from workspace={resume.workspace_id}, page={resume_page}")
+
+ for index, workspace_id in enumerate(remaining):
+ url = base_url + config.path.format(workspace=workspace_id)
+ yield from _iter_endpoint_pages(
+ session, headers, url, params, config, resumable_source_manager, resume_page, workspace_id, logger
+ )
+ resume_page = None # only the resumed-into workspace starts mid-stream
+
+ # Advance the bookmark so a crash between workspaces resumes at the next one.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(KlausResumeConfig(next_page=None, workspace_id=remaining[index + 1]))
+
+
+def get_rows(
+ subdomain: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KlausResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = KLAUS_ENDPOINTS[endpoint]
+ # Re-validate on every sync, not just at source creation: the stored subdomain is
+ # user-supplied and must stay pinned under zendesk.com.
+ base_url = get_base_url(subdomain)
+ headers = _get_headers(api_token)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ # Redirects stay off as defense-in-depth for host pinning. `capture=False` keeps
+ # response bodies out of HTTP sample capture: these endpoints return free-text
+ # customer content (review comments, CSAT feedback, conversations) the name-based
+ # scrubbers can't reliably remove; requests stay metered and logged.
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False, capture=False)
+
+ params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value)
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+
+ if config.fan_out_over_workspaces:
+ yield from _iter_fanout_pages(
+ session, headers, base_url, params, config, resumable_source_manager, resume, logger
+ )
+ else:
+ yield from _iter_endpoint_pages(
+ session,
+ headers,
+ base_url + config.path,
+ params,
+ config,
+ resumable_source_manager,
+ resume.next_page if resume else None,
+ None,
+ logger,
+ )
+
+
+def klaus_source(
+ subdomain: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KlausResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = KLAUS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ subdomain=subdomain,
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # Zendesk QA doesn't document response ordering and exposes no sort param, so
+ # declare desc: the incremental watermark then persists only at successful job
+ # end instead of checkpointing per batch against an unverified ordering.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(subdomain: str, api_token: str) -> tuple[bool, str | None]:
+ try:
+ base_url = get_base_url(subdomain)
+ except ValueError as e:
+ return False, str(e)
+
+ try:
+ # `capture=False` keeps the user listing (names, emails) out of HTTP sample capture.
+ response = make_tracked_session(redact_values=(api_token,), allow_redirects=False, capture=False).get(
+ f"{base_url}/api/export/users",
+ headers=_get_headers(api_token),
+ timeout=30,
+ )
+ except Exception as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid Zendesk QA subdomain or API token"
+ if response.status_code == 429:
+ # The public API is heavily rate limited; a throttled probe still reached the
+ # account's API, so don't block source creation on it.
+ return True, None
+ if response.is_redirect:
+ return (
+ False,
+ "Zendesk QA redirected the request, which usually means the subdomain is incorrect. "
+ "Enter just the subdomain part of yourcompany.zendesk.com",
+ )
+ return False, f"Zendesk QA returned an unexpected status code: {response.status_code}"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/settings.py
new file mode 100644
index 000000000000..c35a6e69941d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/settings.py
@@ -0,0 +1,136 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class KlausEndpointConfig:
+ name: str
+ # Path under https://{subdomain}.zendesk.com/qa. Fan-out paths carry a {workspace} placeholder.
+ path: str
+ # Top-level key the list of records lives under in the response body
+ # (each collection is wrapped, e.g. {"conversations": [...], "pagination": {...}}).
+ data_selector: str
+ # Whether the endpoint accepts page/pageSize params. The catalog endpoints
+ # (users, workspaces, quizzes, scorecards) return everything in one response.
+ paginated: bool = True
+ # Whether the API marks fromDate as required. Full-refresh syncs of these
+ # endpoints pass DEFAULT_FROM_DATE to cover all history.
+ requires_from_date: bool = False
+ # The single advertised incremental option per endpoint is deliberately the
+ # earliest stable timestamp on the row (creation-time, never updated-time):
+ # Zendesk QA doesn't document exactly which timestamp fromDate filters on, and
+ # a watermark tracked on the earliest field can only under-advance — re-fetching
+ # an overlap that merge dedupes on the primary key — never skip rows.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field to partition by, or None to skip partitioning.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Fan out one request stream per workspace (listed via /api/export/workspaces).
+ # Rows get a `workspace_id` column injected so primary keys stay unique table-wide.
+ fan_out_over_workspaces: bool = False
+ page_size: int = 100
+
+
+KLAUS_ENDPOINTS: dict[str, KlausEndpointConfig] = {
+ "reviews": KlausEndpointConfig(
+ name="reviews",
+ path="/api/export/reviews",
+ data_selector="conversations",
+ requires_from_date=True,
+ incremental_fields=[_datetime_incremental_field("createdAtISO")],
+ partition_key="createdAtISO",
+ # Rows are conversation-grain (reviews nested inside). externalId is the
+ # helpdesk ticket id, unique only within its workspace.
+ primary_keys=["workspaceId", "externalId"],
+ ),
+ "autoqa_reviews": KlausEndpointConfig(
+ name="autoqa_reviews",
+ path="/api/export/autoqa/reviews",
+ data_selector="rows",
+ requires_from_date=True,
+ incremental_fields=[_datetime_incremental_field("conversationCreatedAt")],
+ partition_key="conversationCreatedAt",
+ primary_keys=["autoqaReviewId"],
+ ),
+ "autoqa_ratings": KlausEndpointConfig(
+ name="autoqa_ratings",
+ path="/api/export/autoqa/ratings",
+ data_selector="rows",
+ requires_from_date=True,
+ incremental_fields=[_datetime_incremental_field("conversationCreatedAt")],
+ partition_key="conversationCreatedAt",
+ primary_keys=["autoqaRatingId"],
+ ),
+ "csat": KlausEndpointConfig(
+ name="csat",
+ path="/api/export/csat",
+ data_selector="tickets",
+ requires_from_date=True,
+ incremental_fields=[_datetime_incremental_field("ticketCreatedAt")],
+ partition_key="ticketCreatedAt",
+ # CSAT rows have no dedicated id; a ticket can be surveyed more than once,
+ # so the survey creation time disambiguates.
+ primary_keys=["externalTicketId", "csatCreatedAt"],
+ ),
+ "users": KlausEndpointConfig(
+ name="users",
+ path="/api/export/users",
+ data_selector="users",
+ paginated=False,
+ ),
+ "workspaces": KlausEndpointConfig(
+ name="workspaces",
+ path="/api/export/workspaces",
+ data_selector="workspaces",
+ paginated=False,
+ ),
+ "quizzes": KlausEndpointConfig(
+ name="quizzes",
+ path="/api/export/quizzes",
+ data_selector="quizzes",
+ paginated=False,
+ ),
+ "scorecards": KlausEndpointConfig(
+ name="scorecards",
+ path="/api/export/workspace/{workspace}/scorecards",
+ data_selector="data",
+ paginated=False,
+ fan_out_over_workspaces=True,
+ primary_keys=["workspace_id", "id"],
+ ),
+ "disputes": KlausEndpointConfig(
+ name="disputes",
+ path="/api/export/workspace/{workspace}/disputes",
+ data_selector="disputes",
+ # fromDate is optional on disputes; without a live account to verify the
+ # filter actually narrows results server-side, disputes ship full refresh.
+ fan_out_over_workspaces=True,
+ primary_keys=["workspace_id", "disputeId"],
+ ),
+ "calibration_sessions": KlausEndpointConfig(
+ name="calibration_sessions",
+ path="/api/export/workspace/{workspace}/calibration-sessions",
+ data_selector="calibrationSessions",
+ requires_from_date=True,
+ incremental_fields=[_datetime_incremental_field("createdAt")],
+ fan_out_over_workspaces=True,
+ primary_keys=["workspace_id", "id"],
+ ),
+}
+
+ENDPOINTS = tuple(KLAUS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in KLAUS_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/source.py
index 1fa31a6d2142..8a2b30232bdb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/source.py
@@ -1,30 +1,147 @@
-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.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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KlausSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.klaus import (
+ KlausResumeConfig,
+ klaus_source,
+ validate_credentials as validate_klaus_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class KlausSource(SimpleSource[KlausSourceConfig]):
+class KlausSource(ResumableSource[KlausSourceConfig, KlausResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.KLAUS
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `subdomain` determines the host the stored API token is sent to;
+ # retargeting it must re-require the token.
+ return ["subdomain"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.KLAUS,
category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,
label="Klaus",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["zendesk qa", "zendesk", "quality assurance", "conversation reviews"],
+ caption="""Sync your Zendesk QA (formerly Klaus) reviews, AutoQA results, CSAT, disputes, and quality data into the PostHog Data warehouse.
+
+You need an API token, which an admin or account manager can generate in Zendesk QA under **Settings > Auto QA and integrations > API**. The subdomain is the first part of your Zendesk URL (for `yourcompany.zendesk.com`, enter `yourcompany`).
+
+Note that the Zendesk QA public API is heavily rate limited, so large initial syncs can take a while — syncs pace themselves and resume automatically.""",
iconPath="/static/services/klaus.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/klaus",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="subdomain",
+ label="Zendesk subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="yourcompany",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid Zendesk QA credentials. Please check your subdomain and API token and reconnect.",
+ "403 Client Error": "Your Zendesk QA API token does not have access. Please generate a new token and reconnect.",
+ "Unauthorized for url": "Invalid Zendesk QA credentials. Please check your subdomain and API token and reconnect.",
+ "Zendesk QA subdomain must contain only": "The configured Zendesk subdomain is invalid. Enter just the subdomain part of yourcompany.zendesk.com.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.canonical_descriptions import ( # noqa: PLC0415 — keeps the descriptions dict off the import path
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: KlausSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=(fields := INCREMENTAL_FIELDS.get(endpoint)) is not None,
+ supports_append=fields is not None,
+ incremental_fields=fields or [],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: KlausSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_klaus_credentials(config.subdomain, config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KlausResumeConfig]:
+ return ResumableSourceManager[KlausResumeConfig](inputs, KlausResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: KlausSourceConfig,
+ resumable_source_manager: ResumableSourceManager[KlausResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return klaus_source(
+ subdomain=config.subdomain,
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/tests/test_klaus.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/tests/test_klaus.py
new file mode 100644
index 000000000000..b197dea31af3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/tests/test_klaus.py
@@ -0,0 +1,389 @@
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.klaus import (
+ DEFAULT_FROM_DATE,
+ MAX_RETRY_WAIT_SECONDS,
+ KlausResumeConfig,
+ KlausRetryableError,
+ _build_params,
+ _format_datetime,
+ _retry_wait,
+ get_base_url,
+ get_rows,
+ klaus_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.settings import KLAUS_ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.klaus.klaus"
+
+
+def _response(body: dict[str, Any], status: int = 200, headers: dict[str, str] | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ response.is_redirect = status in (301, 302, 303, 307, 308)
+ response.json.return_value = body
+ response.headers = headers or {}
+ response.text = str(body)
+ return response
+
+
+def _manager(resume: KlausResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _drive(
+ endpoint: str,
+ responses: list[MagicMock],
+ manager: MagicMock | None = None,
+ **kwargs: Any,
+) -> tuple[list[list[dict[str, Any]]], MagicMock, MagicMock]:
+ manager = manager if manager is not None else _manager()
+ with patch(f"{MODULE}.make_tracked_session") as MockSession:
+ session = MockSession.return_value
+ session.get.side_effect = responses
+ batches = list(
+ get_rows(
+ subdomain="acme",
+ api_token="test-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager,
+ **kwargs,
+ )
+ )
+ return batches, session, manager
+
+
+def _sent(session: MagicMock) -> list[tuple[str, dict[str, Any]]]:
+ return [(call.args[0], dict(call.kwargs.get("params") or {})) for call in session.get.call_args_list]
+
+
+class TestGetBaseUrl:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("acme", "https://acme.zendesk.com/qa"),
+ (" ACME ", "https://acme.zendesk.com/qa"),
+ ("acme.zendesk.com", "https://acme.zendesk.com/qa"),
+ ("https://acme.zendesk.com/", "https://acme.zendesk.com/qa"),
+ ("my-team2", "https://my-team2.zendesk.com/qa"),
+ ],
+ )
+ def test_normalizes_valid_input(self, raw: str, expected: str) -> None:
+ assert get_base_url(raw) == expected
+
+ @pytest.mark.parametrize(
+ "raw",
+ [
+ "",
+ "evil.com/acme",
+ "acme.evil.com",
+ "acme zendesk",
+ "-acme",
+ "acme?x=1",
+ ],
+ )
+ def test_rejects_host_escapes(self, raw: str) -> None:
+ # A subdomain with dots, slashes, or other URL syntax could splice a
+ # different host into the request URL and receive the bearer token.
+ with pytest.raises(ValueError):
+ get_base_url(raw)
+
+
+class TestBuildParams:
+ def test_required_from_date_defaults_on_full_refresh(self) -> None:
+ params = _build_params(KLAUS_ENDPOINTS["reviews"], False, None)
+ assert params == {"fromDate": _format_datetime(DEFAULT_FROM_DATE)}
+
+ @pytest.mark.parametrize(
+ "last_value",
+ [
+ datetime(2026, 1, 2, 12, 0, tzinfo=UTC),
+ "2026-01-02T12:00:00Z",
+ "2026-01-02T12:00:00+00:00",
+ ],
+ )
+ def test_incremental_value_applies_overlap(self, last_value: Any) -> None:
+ # The watermark is pulled back by the overlap window so an undocumented
+ # exclusive fromDate boundary can't skip same-timestamp rows.
+ params = _build_params(KLAUS_ENDPOINTS["reviews"], True, last_value)
+ assert params == {"fromDate": "2026-01-02T11:00:00Z"}
+
+ @pytest.mark.parametrize("endpoint", ["disputes", "users", "workspaces"])
+ def test_full_refresh_endpoints_without_required_from_date_send_none(self, endpoint: str) -> None:
+ assert _build_params(KLAUS_ENDPOINTS[endpoint], False, None) == {}
+
+
+class TestPagination:
+ def _page(self, items: list[dict[str, Any]], page: int | None, page_size: int, total: int | None = None) -> dict:
+ pagination: dict[str, Any] = {"pageSize": page_size}
+ if page is not None:
+ pagination["page"] = page
+ if total is not None:
+ pagination["total"] = total
+ return {"conversations": items, "pagination": pagination}
+
+ def test_one_indexed_server_advances_from_echo(self) -> None:
+ responses = [
+ _response(self._page([{"externalId": "a"}, {"externalId": "b"}], page=1, page_size=2)),
+ _response(self._page([{"externalId": "c"}], page=2, page_size=2)),
+ ]
+ batches, session, manager = _drive("reviews", responses)
+
+ assert batches == [[{"externalId": "a"}, {"externalId": "b"}], [{"externalId": "c"}]]
+ sent = _sent(session)
+ # The first request omits `page` (indexing base unknown); the second follows
+ # the server's echo.
+ assert "page" not in sent[0][1]
+ assert sent[1][1]["page"] == 2
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ KlausResumeConfig(next_page=2, workspace_id=None)
+ ]
+
+ def test_zero_indexed_server_advances_from_omitted_echo(self) -> None:
+ # proto3 JSON omits zero values, so a 0-indexed first page arrives with no
+ # `page` key in the pagination echo.
+ responses = [
+ _response(self._page([{"externalId": "a"}, {"externalId": "b"}], page=None, page_size=2)),
+ _response(self._page([{"externalId": "c"}], page=1, page_size=2)),
+ ]
+ _, session, _ = _drive("reviews", responses)
+
+ sent = _sent(session)
+ assert "page" not in sent[0][1]
+ assert sent[1][1]["page"] == 1
+
+ def test_server_clamped_page_size_still_detects_full_pages(self) -> None:
+ # We request pageSize=100 but the server clamps to 2 and says so in the echo;
+ # a 2-item page must still count as full rather than terminating the sync.
+ responses = [
+ _response(self._page([{"externalId": "a"}, {"externalId": "b"}], page=1, page_size=2)),
+ _response(self._page([], page=2, page_size=2)),
+ ]
+ batches, session, _ = _drive("reviews", responses)
+
+ assert len(batches) == 1
+ assert _sent(session)[0][1]["pageSize"] == 100
+
+ def test_terminal_short_page_does_not_save_state(self) -> None:
+ responses = [_response(self._page([{"externalId": "a"}], page=1, page_size=2))]
+ batches, _, manager = _drive("reviews", responses)
+
+ assert len(batches) == 1
+ manager.save_state.assert_not_called()
+
+ def test_empty_first_page_yields_nothing(self) -> None:
+ responses = [_response(self._page([], page=1, page_size=2))]
+ batches, _, manager = _drive("reviews", responses)
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ def test_resume_requests_saved_page(self) -> None:
+ manager = _manager(KlausResumeConfig(next_page=5, workspace_id=None))
+ responses = [_response(self._page([{"externalId": "resumed"}], page=5, page_size=2))]
+ _, session, _ = _drive("reviews", responses, manager=manager)
+
+ assert _sent(session)[0][1]["page"] == 5
+
+ def test_stuck_page_echo_raises_instead_of_looping(self) -> None:
+ stuck = self._page([{"externalId": "a"}, {"externalId": "b"}], page=1, page_size=2)
+ responses = [_response(stuck), _response(stuck)]
+
+ with pytest.raises(Exception, match="did not advance"):
+ _drive("reviews", responses)
+
+ def test_incremental_from_date_sent_on_every_page(self) -> None:
+ responses = [
+ _response(self._page([{"externalId": "a"}, {"externalId": "b"}], page=1, page_size=2)),
+ _response(self._page([], page=2, page_size=2)),
+ ]
+ _, session, _ = _drive(
+ "reviews",
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 2, 12, 0, tzinfo=UTC),
+ )
+
+ for _url, params in _sent(session):
+ assert params["fromDate"] == "2026-01-02T11:00:00Z"
+
+
+class TestNonPaginatedEndpoints:
+ def test_users_is_a_single_unpaginated_request(self) -> None:
+ responses = [_response({"users": [{"id": "1", "name": "Alice"}]})]
+ batches, session, manager = _drive("users", responses)
+
+ assert batches == [[{"id": "1", "name": "Alice"}]]
+ sent = _sent(session)
+ assert len(sent) == 1
+ assert "page" not in sent[0][1]
+ assert "pageSize" not in sent[0][1]
+ manager.save_state.assert_not_called()
+
+
+class TestFanOut:
+ def test_fans_out_over_workspaces_and_injects_workspace_id(self) -> None:
+ responses = [
+ _response({"workspaces": [{"id": 1, "name": "Support"}, {"id": 2, "name": "Sales"}]}),
+ _response({"data": [{"id": "10"}]}),
+ _response({"data": [{"id": "10"}]}),
+ ]
+ batches, session, manager = _drive("scorecards", responses)
+
+ urls = [url for url, _ in _sent(session)]
+ assert urls == [
+ "https://acme.zendesk.com/qa/api/export/workspaces",
+ "https://acme.zendesk.com/qa/api/export/workspace/1/scorecards",
+ "https://acme.zendesk.com/qa/api/export/workspace/2/scorecards",
+ ]
+ # The injected workspace id keeps the composite primary key unique table-wide
+ # when the same scorecard id exists in more than one workspace.
+ assert batches == [[{"id": "10", "workspace_id": "1"}], [{"id": "10", "workspace_id": "2"}]]
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ KlausResumeConfig(next_page=None, workspace_id="2")
+ ]
+
+ def test_resume_skips_completed_workspaces(self) -> None:
+ manager = _manager(KlausResumeConfig(next_page=None, workspace_id="2"))
+ responses = [
+ _response({"workspaces": [{"id": 1}, {"id": 2}]}),
+ _response({"data": [{"id": "10"}]}),
+ ]
+ batches, session, _ = _drive("scorecards", responses, manager=manager)
+
+ urls = [url for url, _ in _sent(session)]
+ assert urls == [
+ "https://acme.zendesk.com/qa/api/export/workspaces",
+ "https://acme.zendesk.com/qa/api/export/workspace/2/scorecards",
+ ]
+ assert batches == [[{"id": "10", "workspace_id": "2"}]]
+
+ def test_deleted_bookmark_workspace_restarts_from_scratch(self) -> None:
+ manager = _manager(KlausResumeConfig(next_page=3, workspace_id="99"))
+ responses = [
+ _response({"workspaces": [{"id": 1}]}),
+ _response({"data": [{"id": "10"}]}),
+ ]
+ _, session, _ = _drive("scorecards", responses, manager=manager)
+
+ sent = _sent(session)
+ assert sent[1][0] == "https://acme.zendesk.com/qa/api/export/workspace/1/scorecards"
+ assert "page" not in sent[1][1]
+
+ def test_from_date_applies_to_workspace_requests_but_not_workspace_listing(self) -> None:
+ responses = [
+ _response({"workspaces": [{"id": 1}]}),
+ _response({"calibrationSessions": [{"id": "s1"}], "pagination": {"page": 1, "pageSize": 100}}),
+ ]
+ _, session, _ = _drive("calibration_sessions", responses)
+
+ sent = _sent(session)
+ assert "fromDate" not in sent[0][1]
+ assert sent[1][1]["fromDate"] == _format_datetime(DEFAULT_FROM_DATE)
+
+
+class TestRetry:
+ def test_429_is_retried_honoring_retry_after(self) -> None:
+ responses = [
+ _response({}, status=429, headers={"Retry-After": "30"}),
+ _response({"users": [{"id": "1"}]}),
+ ]
+ with patch("time.sleep") as mock_sleep:
+ batches, _, _ = _drive("users", responses)
+
+ assert batches == [[{"id": "1"}]]
+ assert mock_sleep.call_args.args[0] == 31.0
+
+ def test_retry_wait_caps_excessive_retry_after(self) -> None:
+ retry_state = MagicMock()
+ retry_state.outcome.exception.return_value = KlausRetryableError("throttled", retry_after=100_000)
+ assert _retry_wait(retry_state) == MAX_RETRY_WAIT_SECONDS
+
+
+class TestSourceResponse:
+ def test_reviews_response_shape(self) -> None:
+ response = klaus_source("acme", "token", "reviews", MagicMock(), _manager())
+
+ assert response.name == "reviews"
+ # Conversation externalId is the helpdesk ticket id, only unique per workspace.
+ assert response.primary_keys == ["workspaceId", "externalId"]
+ # Response ordering is undocumented, so the watermark must only persist at
+ # successful job end.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAtISO"]
+
+ def test_unpartitioned_endpoint_has_no_partition_settings(self) -> None:
+ response = klaus_source("acme", "token", "users", MagicMock(), _manager())
+
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid"),
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ # A throttled probe still reached the account's API; the aggressive public
+ # rate limit must not block source creation.
+ (429, True),
+ (500, False),
+ ],
+ )
+ def test_status_code_mapping(self, status_code: int, expected_valid: bool) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as MockSession:
+ MockSession.return_value.get.return_value = _response({}, status=status_code)
+
+ valid, error = validate_credentials("acme", "test-token")
+
+ assert valid is expected_valid
+ if expected_valid:
+ assert error is None
+ else:
+ assert error is not None
+
+ def test_invalid_subdomain_fails_without_a_request(self) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as MockSession:
+ valid, error = validate_credentials("acme.evil.com", "test-token")
+
+ assert valid is False
+ assert error is not None
+ MockSession.assert_not_called()
+
+ def test_network_error_returns_message(self) -> None:
+ with patch(f"{MODULE}.make_tracked_session") as MockSession:
+ MockSession.return_value.get.side_effect = Exception("boom")
+ valid, error = validate_credentials("acme", "test-token")
+
+ assert valid is False
+ assert error == "boom"
+
+
+class TestGetRowsIsLazy:
+ def test_no_request_until_iterated(self) -> None:
+ # source_for_pipeline builds the SourceResponse eagerly; the first HTTP call
+ # must not happen until the pipeline starts consuming items.
+ with patch(f"{MODULE}.make_tracked_session") as MockSession:
+ response = klaus_source("acme", "token", "users", MagicMock(), _manager())
+ MockSession.assert_not_called()
+
+ MockSession.return_value.get.return_value = _response({"users": [{"id": "1"}]})
+ items = response.items()
+ assert isinstance(items, Iterator)
+ assert list(items) == [[{"id": "1"}]]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/tests/test_klaus_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/tests/test_klaus_source.py
new file mode 100644
index 000000000000..b733824eb028
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/tests/test_klaus_source.py
@@ -0,0 +1,149 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KlausSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.klaus import KlausResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.source import KlausSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"reviews", "autoqa_reviews", "autoqa_ratings", "csat", "calibration_sessions"}
+FULL_REFRESH_ENDPOINTS = {"users", "workspaces", "quizzes", "scorecards", "disputes"}
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "reviews",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestKlausSource:
+ def setup_method(self) -> None:
+ self.source = KlausSource()
+ self.team_id = 123
+ self.config = KlausSourceConfig(subdomain="acme", api_token="test-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.KLAUS
+
+ def test_subdomain_is_a_connection_host_field(self) -> None:
+ # Changing the subdomain retargets where the stored token is sent, so it must
+ # force the token to be re-entered.
+ assert self.source.connection_host_fields == ["subdomain"]
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Klaus"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/klaus"
+
+ subdomain_field, api_token_field = config.fields
+ assert isinstance(subdomain_field, SourceFieldInputConfig)
+ assert subdomain_field.name == "subdomain"
+ assert subdomain_field.type == SourceFieldInputConfigType.TEXT
+ assert subdomain_field.required is True
+
+ assert isinstance(api_token_field, SourceFieldInputConfig)
+ assert api_token_field.name == "api_token"
+ assert api_token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_token_field.required is True
+ assert api_token_field.secret is True
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", "Unauthorized for url"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_incremental_flags(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ assert {name for name, s in schemas.items() if s.supports_incremental} == INCREMENTAL_ENDPOINTS
+ assert {name for name, s in schemas.items() if not s.supports_incremental} == FULL_REFRESH_ENDPOINTS
+ for name in INCREMENTAL_ENDPOINTS:
+ assert schemas[name].incremental_fields, name
+ for name in FULL_REFRESH_ENDPOINTS:
+ assert schemas[name].incremental_fields == [], name
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["reviews", "nonexistent"])
+ assert [s.name for s in schemas] == ["reviews"]
+
+ def test_get_documented_tables_lists_static_catalog(self) -> None:
+ # lists_tables_without_credentials must stay in sync with a get_schemas that
+ # does no I/O, so the public docs can render the table catalog.
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ ((True, None), True, None),
+ ((False, "Invalid Zendesk QA subdomain or API token"), False, "Invalid Zendesk QA subdomain or API token"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.klaus.source.validate_klaus_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.subdomain, self.config.api_token)
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is KlausResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.klaus.source.klaus_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ logger = mock.MagicMock()
+ inputs = _make_inputs(
+ schema_name="autoqa_reviews",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ logger=logger,
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ subdomain="acme",
+ api_token="test-token",
+ endpoint="autoqa_reviews",
+ logger=logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ )