: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(warehouse_sources): add klaus quiz responses, overviews, and leaderboard tables (#113342)
Tom Owers5672d42dd371
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 9bcfc473c883..83a81706893c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -4778,10 +4778,10 @@ Today (10): `autoqa_ratings`, `autoqa_reviews`, `calibration_sessions`, `csat`,Diffed against: <https://pub.klausapp.com/public-export-api.swagger.json>-- [ ] `/api/export/quizzes/{id}/responses` — individual quiz responses per user — quizzes alone is only the quiz definition, so pass rates and knowledge gaps are unqueryable (high)-- [ ] `/api/export/conversations/search` — the conversation records that reviews and AutoQA ratings attach to; without them scores cannot be tied back to channel, queue, or handling time (high)-- [ ] `/api/export/quizzes/{id}/overview` — per-quiz aggregate results, the vendor's own summary view (medium)-- [ ] `/api/export/quizzes/leaderboard` — agent ranking dimension across quizzes (medium)+- [x] `/api/export/quizzes/{id}/responses` — individual quiz responses per user — quizzes alone is only the quiz definition, so pass rates and knowledge gaps are unqueryable (high). Added as `quiz_responses` (fan-out over `quizzes`).+- [ ] `/api/export/conversations/search` — the conversation records that reviews and AutoQA ratings attach to; without them scores cannot be tied back to channel, queue, or handling time (high) — skipped: a POST lookup that needs an `endUserEmail` in the body and returns only `externalId` and `externalLink` per match, so it cannot list conversations and carries none of the claimed channel, queue, or handling-time fields.+- [x] `/api/export/quizzes/{id}/overview` — per-quiz aggregate results, the vendor's own summary view (medium). Added as `quiz_overviews` (fan-out over `quizzes`).+- [x] `/api/export/quizzes/leaderboard` — agent ranking dimension across quizzes (medium). Added as `quiz_leaderboard`.Note: Now branded Zendesk QA. pub.klausapp.com hosts two Swagger 2.0 specs; the relevant one is public-export-api.swagger.json (18 paths) — the sibling public-import-api.swagger.json is write-only ingestion and irrelevant here. PostHog's 10 tables map 1:1 onto the workspace-scoped export endpoints; the only genuine holes are the quiz sub-resources and the POST-based conversation search (which needs a request body, so it is more work than the plain GET exports).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.pyindex 6383c395fc71..4f875bfc8d60 100644--- 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@@ -157,4 +157,47 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"conversations": "Conversations included in the session.",},},+ "quiz_responses": {+ "description": "Responses submitted to each quiz, one row per user response with its score.",+ "docs_url": _DOCS_URL,+ "columns": {+ "quiz_id": "Identifier of the quiz the response belongs to.",+ "responseId": "Unique identifier of the quiz response.",+ "userId": "Identifier of the user who responded.",+ "userName": "Name of the user who responded.",+ "correctAnswerPercentage": "Share of the quiz questions the user answered correctly, as a percentage.",+ },+ },+ "quiz_overviews": {+ "description": "Per-quiz results overview, with answer statistics for each question and option.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier of the quiz.",+ "quiz_id": "Identifier of the quiz (same as id).",+ "name": "Name of the quiz.",+ "description": "Description of the quiz.",+ "status": "Publication status of the quiz.",+ "createdBy": "Identifier of the user who created the quiz.",+ "updatedBy": "Identifier of the user who last updated the quiz.",+ "createdAt": "When the quiz was created.",+ "updatedAt": "When the quiz was last updated.",+ "publishedDate": "When the quiz was published.",+ "responseCount": "Number of responses submitted to the quiz.",+ "fields": "Quiz questions with their options and how often each option was selected.",+ "averageScorePercentage": "Average score across responses, as a percentage.",+ },+ },+ "quiz_leaderboard": {+ "description": "Quiz leaderboard, one row per user ranked by quiz performance across all quizzes.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Identifier of the user.",+ "name": "Name of the user.",+ "avatar": "Link to the user's avatar image.",+ "quizzesTaken": "Number of quizzes the user has taken.",+ "ranking": "Position of the user on the leaderboard.",+ "averageScorePercentage": "Average score of the user across quizzes, as a percentage.",+ "requesterCanManageAnyQuiz": "Whether the API token's user can manage any quiz.",+ },+ },}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.pyindex 0c67f3ab923e..94b7c982d7bb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/klaus.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/klaus.py@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.klaus.settings import (KLAUS_ENDPOINTS,KlausEndpointConfig,+ KlausFanOutParent,)REQUEST_TIMEOUT = 60@@ -38,15 +39,16 @@ class KlausRetryableError(Exception):self.retry_after = retry_after[email protected](frozen=False)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.+ # to a parent 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.+ # The parent (workspace or quiz) currently being processed for fan-out endpoints.+ # A stable ID bookmark (not a positional index) so parents added/removed between+ # a crash and the retry can't resume us into the wrong one. The name stays+ # `workspace_id` so state saved by running syncs still loads.workspace_id: str | None = None@@ -187,10 +189,10 @@ def _iter_endpoint_pages(config: KlausEndpointConfig,resumable_source_manager: ResumableSourceManager[KlausResumeConfig],resume_page: int | None,- workspace_id: str | None,+ parent: tuple[str, str] | None,logger: FilteringBoundLogger,) -> Iterator[list[dict[str, Any]]]:- """Page through one endpoint (or one workspace of a fan-out endpoint), yielding row batches.+ """Page through one endpoint (or one parent of a fan-out endpoint), yielding row batches.The docs don't say whether page numbering starts at 0 or 1, so the first requestomits `page` and later requests derive the next index from the response's@@ -208,12 +210,16 @@ def _iter_endpoint_pages(request_params["page"] = next_pagedata = _fetch_page(session, url, request_params, headers, logger)- items = data.get(config.data_selector) or []+ if config.data_selector is None:+ items = [data] if data else []+ else:+ 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 parent is not None:+ parent_column, parent_id = parent+ items = [{**item, parent_column: parent_id} for item in items]if not config.paginated:yield items@@ -238,17 +244,20 @@ def _iter_endpoint_pages(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))+ resumable_source_manager.save_state(+ KlausResumeConfig(next_page=next_page, workspace_id=parent[1] if parent is not None else None)+ )-def _get_workspace_ids(+def _get_parent_ids(session: requests.Session,headers: dict[str, str],base_url: str,+ fan_out: KlausFanOutParent,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 []]+ data = _fetch_page(session, base_url + fan_out.list_path, {}, headers, logger)+ return [str(parent["id"]) for parent in data.get(fan_out.data_selector) or []]def _iter_fanout_pages(@@ -257,30 +266,39 @@ def _iter_fanout_pages(base_url: str,params: dict[str, Any],config: KlausEndpointConfig,+ fan_out: KlausFanOutParent,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)+ parent_ids = _get_parent_ids(session, headers, base_url, fan_out, 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+ # Resolve the saved parent bookmark to the slice still to process. If the+ # bookmarked parent no longer exists, start over from the first one — merge# dedupes the re-pulled rows on the primary key.- remaining = workspace_ids+ remaining = parent_idsresume_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) :]+ if resume is not None and resume.workspace_id is not None and resume.workspace_id in parent_ids:+ remaining = parent_ids[parent_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}")+ logger.debug(f"Zendesk QA: resuming {config.name} from parent={resume.workspace_id}, page={resume_page}")- for index, workspace_id in enumerate(remaining):- url = base_url + config.path.format(workspace=workspace_id)+ for index, parent_id in enumerate(remaining):+ url = base_url + config.path.format(**{fan_out.path_param: parent_id})yield from _iter_endpoint_pages(- session, headers, url, params, config, resumable_source_manager, resume_page, workspace_id, logger+ session,+ headers,+ url,+ params,+ config,+ resumable_source_manager,+ resume_page,+ (fan_out.parent_column, parent_id),+ logger,)- resume_page = None # only the resumed-into workspace starts mid-stream+ resume_page = None # only the resumed-into parent starts mid-stream- # Advance the bookmark so a crash between workspaces resumes at the next one.+ # Advance the bookmark so a crash between parents resumes at the next one.if index + 1 < len(remaining):resumable_source_manager.save_state(KlausResumeConfig(next_page=None, workspace_id=remaining[index + 1]))@@ -309,9 +327,9 @@ def get_rows(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:+ if config.fan_out is not None:yield from _iter_fanout_pages(- session, headers, base_url, params, config, resumable_source_manager, resume, logger+ session, headers, base_url, params, config, config.fan_out, resumable_source_manager, resume, logger)else:yield from _iter_endpoint_pages(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.pyindex c35a6e69941d..e8b534a37578 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/klaus/settings.py@@ -13,14 +13,40 @@ def _datetime_incremental_field(name: str) -> IncrementalField:}-@dataclass+@dataclass(frozen=True)+class KlausFanOutParent:+ list_path: str+ data_selector: str+ # Placeholder in the child endpoint path that receives the parent id.+ path_param: str+ # Column injected into child rows so primary keys stay unique table-wide.+ parent_column: str+++WORKSPACES_PARENT = KlausFanOutParent(+ list_path="/api/export/workspaces",+ data_selector="workspaces",+ path_param="workspace",+ parent_column="workspace_id",+)++QUIZZES_PARENT = KlausFanOutParent(+ list_path="/api/export/quizzes",+ data_selector="quizzes",+ path_param="id",+ parent_column="quiz_id",+)+++@dataclass(frozen=False)class KlausEndpointConfig:name: str- # Path under https://{subdomain}.zendesk.com/qa. Fan-out paths carry a {workspace} placeholder.+ # Path under https://{subdomain}.zendesk.com/qa. Fan-out paths carry the parent's path_param 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+ # None means the whole body is a single record.+ data_selector: Optional[str]# Whether the endpoint accepts page/pageSize params. The catalog endpoints# (users, workspaces, quizzes, scorecards) return everything in one response.paginated: bool = True@@ -36,9 +62,8 @@ class KlausEndpointConfig:# Stable creation-time field to partition by, or None to skip partitioning.partition_key: Optional[str] = Noneprimary_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+ # Fan out one request stream per parent record (e.g. per workspace).+ fan_out: Optional[KlausFanOutParent] = Nonepage_size: int = 100@@ -106,7 +131,7 @@ KLAUS_ENDPOINTS: dict[str, KlausEndpointConfig] = {path="/api/export/workspace/{workspace}/scorecards",data_selector="data",paginated=False,- fan_out_over_workspaces=True,+ fan_out=WORKSPACES_PARENT,primary_keys=["workspace_id", "id"],),"disputes": KlausEndpointConfig(@@ -115,7 +140,7 @@ KLAUS_ENDPOINTS: dict[str, KlausEndpointConfig] = {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,+ fan_out=WORKSPACES_PARENT,primary_keys=["workspace_id", "disputeId"],),"calibration_sessions": KlausEndpointConfig(@@ -124,9 +149,30 @@ KLAUS_ENDPOINTS: dict[str, KlausEndpointConfig] = {data_selector="calibrationSessions",requires_from_date=True,incremental_fields=[_datetime_incremental_field("createdAt")],- fan_out_over_workspaces=True,+ fan_out=WORKSPACES_PARENT,primary_keys=["workspace_id", "id"],),+ "quiz_responses": KlausEndpointConfig(+ name="quiz_responses",+ path="/api/export/quizzes/{id}/responses",+ data_selector="responses",+ paginated=False,+ fan_out=QUIZZES_PARENT,+ primary_keys=["quiz_id", "responseId"],+ ),+ "quiz_overviews": KlausEndpointConfig(+ name="quiz_overviews",+ path="/api/export/quizzes/{id}/overview",+ data_selector=None,+ paginated=False,+ fan_out=QUIZZES_PARENT,+ ),+ "quiz_leaderboard": KlausEndpointConfig(+ name="quiz_leaderboard",+ path="/api/export/quizzes/leaderboard",+ data_selector="leaderboardUsers",+ paginated=False,+ ),}ENDPOINTS = tuple(KLAUS_ENDPOINTS.keys())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.pyindex b197dea31af3..9661727db262 100644--- 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@@ -282,6 +282,35 @@ class TestFanOut:assert sent[1][0] == "https://acme.zendesk.com/qa/api/export/workspace/1/scorecards"assert "page" not in sent[1][1]+ def test_fans_out_over_quizzes_and_injects_quiz_id(self) -> None:+ responses = [+ _response({"quizzes": [{"id": "7", "name": "Refunds"}, {"id": "8", "name": "Tone"}]}),+ _response({"responses": [{"responseId": "100", "userId": "1", "correctAnswerPercentage": "80"}]}),+ _response({}),+ ]+ batches, session, _ = _drive("quiz_responses", responses)++ assert [url for url, _ in _sent(session)] == [+ "https://acme.zendesk.com/qa/api/export/quizzes",+ "https://acme.zendesk.com/qa/api/export/quizzes/7/responses",+ "https://acme.zendesk.com/qa/api/export/quizzes/8/responses",+ ]+ # proto3 JSON drops an empty repeated field, so a quiz with no responses+ # returns `{}` and must yield nothing.+ assert batches == [[{"responseId": "100", "userId": "1", "correctAnswerPercentage": "80", "quiz_id": "7"}]]++ def test_single_object_response_becomes_one_row_per_quiz(self) -> None:+ responses = [+ _response({"quizzes": [{"id": "7"}]}),+ _response({"id": "7", "name": "Refunds", "responseCount": "3", "fields": [{"id": "1"}]}),+ ]+ batches, session, _ = _drive("quiz_overviews", responses)++ assert _sent(session)[1][0] == "https://acme.zendesk.com/qa/api/export/quizzes/7/overview"+ assert batches == [+ [{"id": "7", "name": "Refunds", "responseCount": "3", "fields": [{"id": "1"}], "quiz_id": "7"}]+ ]+def test_from_date_applies_to_workspace_requests_but_not_workspace_listing(self) -> None:responses = [_response({"workspaces": [{"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.pyindex 3bc5c2546962..beea9064a599 100644--- 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@@ -3,7 +3,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.klaus.settfrom products.warehouse_sources.backend.temporal.data_imports.sources.klaus.source import KlausSourceINCREMENTAL_ENDPOINTS = {"reviews", "autoqa_reviews", "autoqa_ratings", "csat", "calibration_sessions"}-FULL_REFRESH_ENDPOINTS = {"users", "workspaces", "quizzes", "scorecards", "disputes"}+FULL_REFRESH_ENDPOINTS = {+ "users",+ "workspaces",+ "quizzes",+ "scorecards",+ "disputes",+ "quiz_responses",+ "quiz_overviews",+ "quiz_leaderboard",+}class TestKlausSource: