: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): add 2 missing tables to the OpinionStage source (#116416)
Tom Owers2f3a70efca21
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 3ee21aa7049d..b51da011a26b 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@@ -8813,8 +8813,8 @@ Today (1): `items`Diffed against: <https://api.opinionstage.com/api-docs/api/v2/openapi.yaml>-- [ ] `/api/v2/items/{itemId}/responses` — the actual respondent-level answer data — the entire point of the Public Result API; today only the widget list is synced (high)-- [ ] `/api/v2/items/{itemId}/questions` — lookup table resolving the question IDs carried on response rows (high)+- [x] `/api/v2/items/{itemId}/responses` — the actual respondent-level answer data — the entire point of the Public Result API; today only the widget list is synced (high)+- [x] `/api/v2/items/{itemId}/questions` — lookup table resolving the question IDs carried on response rows (high)Note: The vendor OpenAPI spec (title 'Public Result API') defines exactly 5 operations: list items, get item, list responses, get response, list questions. PostHog implements only list items. products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/settings.py explicitly defers responses and questions as 'fan-out (they require an item id) and are intentionally excluded from v1' — so the gap is known and deliberate, but it is the whole analytical payload.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/canonical_descriptions.pyindex 9d432c3d3106..f27ebf9eebc8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/canonical_descriptions.py@@ -15,4 +15,25 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"attributes": "The item's attributes, including its title, content format/kind, publication state, and created/modified timestamps.",},},+ "responses": {+ "description": "A single submission of an Opinion Stage item by a respondent, with the answer to each question.",+ "docs_url": "https://api.opinionstage.com/api-docs/api/v2/openapi.yaml",+ "columns": {+ "id": "The unique identifier for the response.",+ "item_id": "The ID of the item (widget) that the response belongs to.",+ "type": "The JSON:API resource type. Always 'responses'.",+ "attributes": "The response's attributes: creation timestamp, the answers (question ID, selected options, free text, checked flag), the result shown, the UTM source, and the completion duration.",+ "links": "Links to the response in the API and to the page that hosts the item.",+ },+ },+ "questions": {+ "description": "A question of an Opinion Stage item. Use it to resolve the question IDs on response answers.",+ "docs_url": "https://api.opinionstage.com/api-docs/api/v2/openapi.yaml",+ "columns": {+ "id": "The unique identifier for the question.",+ "item_id": "The ID of the item (widget) that the question belongs to.",+ "type": "The JSON:API resource type. Always 'questions'.",+ "attributes": "The question's attributes: title, kind (text, select, or boolean), whether it is part of the lead form, and created/modified timestamps.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/opinion_stage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/opinion_stage.pyindex b39db2ae3ad5..beea5a6a6611 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/opinion_stage.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/opinion_stage.py@@ -1,15 +1,20 @@-import dataclassesfrom typing import Any, Optionalfrom requests import Request, Responsefrom requests.auth import HTTPBasicAuth+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -18,9 +23,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.opinion_st)OPINION_STAGE_BASE_URL = "https://api.opinionstage.com"-# JSON:API `page[size]`. The API does not document a hard maximum, so a moderate page keeps the-# per-page payload bounded while minimising round trips for the small item/widget catalogue.-PAGE_SIZE = 100# Cheap endpoint used to confirm the API key is genuine. The personal API key is account-wide, so# one probe validates access to every list endpoint.DEFAULT_PROBE_PATH = "/api/v2/items"@@ -32,11 +34,14 @@ PAGE_NUMBER_PARAM = "page[number]"PAGE_SIZE_PARAM = "page[size]"+@frozenclass OpinionStageResumeConfig:# Next page to fetch (1-indexed). Page-number pagination is deterministic, so a crashed# full-refresh sync resumes from the page after the last one yielded; merge dedupes on `id`.next_page: int = 1+ # Progress of an endpoint that is listed once per item: the items that are done, the item in+ # progress, and the page cursor of that item. The shared fan-out helper owns the shape.+ fanout_state: Optional[dict[str, Any]] = Nonedef _headers(api_key: str) -> dict[str, str]:@@ -49,8 +54,10 @@ class OpinionStagePaginator(BasePaginator):"""JSON:API page-number pagination.Increments ``page[number]`` (1-indexed) with a constant ``page[size]`` and terminates when the- response body's ``links.next`` is null/absent OR the page is empty (a defensive guard so a stale- ``next`` link can't loop forever). ``page[size]`` is set once via the endpoint params, so this+ response body reports no further page OR the page is empty (a defensive guard so a stale+ ``next`` link can't loop forever). A further page is reported by ``links.next``, or by+ ``meta.page.current`` below ``meta.page.total``: the OpenAPI spec documents the ``meta.page``+ counters but no ``next`` link. ``page[size]`` is set once via the endpoint params, so thispaginator only manages ``page[number]``."""@@ -68,11 +75,7 @@ class OpinionStagePaginator(BasePaginator):if not data:self._has_next_page = Falsereturn- try:- next_link = (response.json().get("links") or {}).get("next")- except Exception:- next_link = None- if not next_link:+ if not _has_next_page(response, requested_page=self.page):self._has_next_page = Falsereturnself.page += 1@@ -97,6 +100,76 @@ class OpinionStagePaginator(BasePaginator):return f"OpinionStagePaginator(page={self.page})"+def _has_next_page(response: Response, requested_page: int) -> bool:+ try:+ body = response.json()+ if (body.get("links") or {}).get("next"):+ return True+ page = (body.get("meta") or {}).get("page") or {}+ current = int(page["current"])+ # A `current` behind the page we asked for means the server ignored `page[number]`: stop+ # rather than re-fetch the same page forever.+ return requested_page <= current < int(page["total"])+ except Exception:+ return False+++def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": OPINION_STAGE_BASE_URL,+ # Only the non-secret Accept header; the key rides on the framework auth below.+ "headers": _headers(api_key),+ # HTTP Basic: the personal API key is the username and the password is blank.+ "auth": {"type": "http_basic", "username": api_key, "password": ""},+ "paginator": OpinionStagePaginator(),+ }+++def _fanout_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[OpinionStageResumeConfig],+) -> SourceResponse:+ config = OPINION_STAGE_ENDPOINTS[endpoint]+ assert config.fanout is not None++ initial_fanout_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ initial_fanout_state = resume.fanout_state++ def save_fanout_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state is not None:+ resumable_source_manager.save_state(OpinionStageResumeConfig(fanout_state=state))++ resource = build_dependent_resource(+ endpoint_configs=OPINION_STAGE_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=_client_config(api_key),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ page_size_param=PAGE_SIZE_PARAM,+ parent_endpoint_extra={"data_selector": "data", "data_selector_malformed_retryable": True},+ child_endpoint_extra={"data_selector": "data", "data_selector_malformed_retryable": True},+ resume_hook=save_fanout_checkpoint,+ initial_paginator_state=initial_fanout_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )++def opinion_stage_source(api_key: str,endpoint: str,@@ -106,23 +179,18 @@ def opinion_stage_source(db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = OPINION_STAGE_ENDPOINTS[endpoint]+ if config.fanout is not None:+ return _fanout_source(api_key, endpoint, team_id, job_id, resumable_source_manager)rest_config: RESTAPIConfig = {- "client": {- "base_url": OPINION_STAGE_BASE_URL,- # Only the non-secret Accept header; the key rides on the framework auth below.- "headers": _headers(api_key),- # HTTP Basic: the personal API key is the username and the password is blank.- "auth": {"type": "http_basic", "username": api_key, "password": ""},- "paginator": OpinionStagePaginator(),- },+ "client": _client_config(api_key),"resource_defaults": {},"resources": [{"name": endpoint,"endpoint": {"path": config.path,- "params": {PAGE_SIZE_PARAM: PAGE_SIZE},+ "params": {PAGE_SIZE_PARAM: config.page_size},# JSON:API always wraps a collection under a top-level `data` list."data_selector": "data",# A 200 whose body isn't the expected `{"data": [...]}` shape is malformed fordiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/settings.pyindex 16d864524ba3..61096fc3eac7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/settings.py@@ -1,26 +1,65 @@-from dataclasses import dataclass, field+from dataclasses import field+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField+# JSON:API `page[size]`. The API does not document a hard maximum, so a moderate page keeps the+# per-page payload bounded while minimising round trips.+PAGE_SIZE = 100+-@dataclass+@frozenclass OpinionStageEndpointConfig:name: strpath: str# JSON:API resource objects carry a top-level `id`, unique within the account, so it is a safe# primary key.primary_keys: list[str] = field(default_factory=lambda: ["id"])+ page_size: int = PAGE_SIZE+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ fanout: DependentEndpointConfig | None = None+++def _per_item() -> DependentEndpointConfig:+ return DependentEndpointConfig(+ parent_name="items",+ resolve_param="item_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "item_id"},+ # An item removed between the item listing and its child request answers 404. That item+ # has no rows to sync, so it must not fail the items that remain.+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ )-# Opinion Stage Public Result API list endpoints. Only account-level collections that can be listed-# without a parent id are included. Per-item `responses` and `questions` are fan-out (they require an-# item id) and are intentionally excluded from v1.+# Opinion Stage Public Result API list endpoints. `items` is the account-level collection.+# `responses` and `questions` are listed once per item.## All are full-refresh only: although the docs mention date-range filtering, the filter parameter# names are not defined in the OpenAPI spec, so there is no incremental cursor we can advance safely# (see the implementing-warehouse-sources skill).OPINION_STAGE_ENDPOINTS: dict[str, OpinionStageEndpointConfig] = {"items": OpinionStageEndpointConfig(name="items", path="/api/v2/items"),+ # The spec does not say that a response or question id is unique across items, so the item id+ # is part of the key.+ "responses": OpinionStageEndpointConfig(+ name="responses",+ path="/api/v2/items/{item_id}/responses",+ primary_keys=["item_id", "id"],+ fanout=_per_item(),+ ),+ "questions": OpinionStageEndpointConfig(+ name="questions",+ path="/api/v2/items/{item_id}/questions",+ primary_keys=["item_id", "id"],+ fanout=_per_item(),+ ),}ENDPOINTS = tuple(OPINION_STAGE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/source.pyindex 67e3bbc1b851..213f23f61f0b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/source.py@@ -54,7 +54,7 @@ class OpinionStageSource(ResumableSource[OpinionStageSourceConfig, OpinionStageRreleaseStatus=ReleaseStatus.ALPHA,caption="""Enter your Opinion Stage personal API key to pull your interactive content data into the PostHog Data warehouse.-You can find your API key on your account settings page in [Opinion Stage](https://www.opinionstage.com/). The key grants read access to your items (quizzes, surveys, and forms) via the Public Result API.+You can find your API key on your account settings page in [Opinion Stage](https://www.opinionstage.com/). The key grants read access to your items (quizzes, surveys, and forms), their questions, and their responses via the Public Result API.""",iconPath="/static/services/opinion_stage.png",docsUrl="https://posthog.com/docs/cdp/sources/opinion-stage",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage.pyindex b1258243e4b7..a2f0463e1421 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opinion_stage/tests/test_opinion_stage.py@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tesScriptedResponse,SourceDriver,always,+ route,scripted_network,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.opinionstage import (@@ -28,6 +29,13 @@ def _page(items: list[dict[str, Any]], next_link: str | None) -> ScriptedResponsreturn ScriptedResponse(json={"data": items, "meta": {}, "links": {"self": "s", "next": next_link}})+def _counted_page(items: list[dict[str, Any]], current: int, total: int) -> ScriptedResponse:+ # The envelope the OpenAPI spec documents: page counters under `meta.page` and no `links.next`.+ return ScriptedResponse(+ json={"data": items, "meta": {"page": {"current": current, "size": 100, "total": total}}, "links": {}}+ )++class TestOpinionStage:@staticmethoddef _driver() -> SourceDriver:@@ -45,6 +53,107 @@ class TestOpinionStage:# Page 1 is never fetched on resume — the first request targets page 2.assert result.params("page[number]") == ["2", "3"]+ @parameterized.expand([("responses",), ("questions",)])+ def test_fan_out_walks_every_item_and_every_child_page(self, endpoint: str) -> None:+ result = self._driver().run(+ endpoint,+ route(+ {+ "/api/v2/items": [+ _counted_page([{"id": "item-a"}, {"id": "item-gone"}], current=1, total=2),+ _counted_page([{"id": "item-b"}], current=2, total=2),+ ],+ f"/api/v2/items/item-a/{endpoint}": [+ _counted_page([{"id": "1", "attributes": {"title": None}}], current=1, total=2),+ _page([{"id": "2"}], next_link=None),+ ],+ f"/api/v2/items/item-gone/{endpoint}": [+ ScriptedResponse(+ status=404, json={"errors": [{"status": "404", "title": "resource not found"}]}+ )+ ],+ f"/api/v2/items/item-b/{endpoint}": [_page([{"id": "1"}], next_link=None)],+ }+ ),+ )++ assert result.raised is None+ assert result.response is not None+ assert result.response.primary_keys == ["item_id", "id"]+ assert [(row["item_id"], row["id"]) for row in result.rows] == [+ ("item-a", "1"),+ ("item-a", "2"),+ ("item-b", "1"),+ ]+ assert result.rows[0]["attributes"] == {"title": None}+ assert [(request.path, request.param("page[number]")) for request in result.requests] == [+ ("/api/v2/items", "1"),+ (f"/api/v2/items/item-a/{endpoint}", "1"),+ (f"/api/v2/items/item-a/{endpoint}", "2"),+ (f"/api/v2/items/item-gone/{endpoint}", "1"),+ ("/api/v2/items", "2"),+ (f"/api/v2/items/item-b/{endpoint}", "1"),+ ]+ assert set(result.params("page[size]")) == {"100"}++ def test_fan_out_resumes_inside_the_item_in_progress(self) -> None:+ result = self._driver().run(+ "responses",+ route(+ {+ "/api/v2/items": [_page([{"id": "item-a"}, {"id": "item-b"}, {"id": "item-c"}], next_link=None)],+ "/api/v2/items/item-b/responses": [_page([{"id": "9"}], next_link=None)],+ "/api/v2/items/item-c/responses": [_page([], next_link=None)],+ }+ ),+ resume_state=OpinionStageResumeConfig(+ fanout_state={+ "completed": ["/api/v2/items/item-a/responses"],+ "current": "/api/v2/items/item-b/responses",+ "child_state": {"next_page": 3},+ }+ ),+ )++ assert result.raised is None+ assert [(row["item_id"], row["id"]) for row in result.rows] == [("item-b", "9")]+ assert [(request.path, request.param("page[number]")) for request in result.requests] == [+ ("/api/v2/items", "1"),+ ("/api/v2/items/item-b/responses", "3"),+ ("/api/v2/items/item-c/responses", "1"),+ ]+ assert result.committed_states++ @parameterized.expand(+ [+ ("next_link_without_counters", {"links": {"next": "p2"}}, ["1", "2"]),+ ("counters_without_next_link", {"meta": {"page": {"current": 1, "total": 2}}, "links": {}}, ["1", "2"]),+ ("last_page_by_counters", {"meta": {"page": {"current": 1, "total": 1}}}, ["1"]),+ ("malformed_counters", {"meta": {"page": {"current": "x"}}}, ["1"]),+ ("no_paging_fields", {}, ["1"]),+ ]+ )+ def test_next_page_signal(self, _name: str, envelope: dict[str, Any], expected_pages: list[str]) -> None:+ result = self._driver().run(+ "items",+ [ScriptedResponse(json={"data": [{"id": "1"}], **envelope}), _page([{"id": "2"}], next_link=None)][+ : len(expected_pages)+ ],+ )++ assert result.raised is None+ assert result.params("page[number]") == expected_pages++ def test_counters_stuck_on_page_1_stop_the_walk(self) -> None:+ stuck = {"meta": {"page": {"current": 1, "total": 5}}, "links": {}}+ result = self._driver().run(+ "items",+ always(ScriptedResponse(json={"data": [{"id": "1"}], **stuck})),+ )++ assert result.raised is None+ assert result.params("page[number]") == ["1", "2"]+def test_empty_data_yields_no_rows(self) -> None:result = self._driver().run("items", [_page([], next_link=None)])@@ -102,7 +211,6 @@ class TestOpinionStage:assert result.raised is Noneassert result.response is not Noneassert result.response.name == endpoint- assert result.response.primary_keys == ["id"]# JSON:API items carry no guaranteed stable creation timestamp column, so we don't partition.assert result.response.partition_mode is None