:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement surveymonkey import source (#61157)
Tom Owers98456857c90a
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 8e7e32404dc1..32e90d5e94a0 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -97,6 +97,7 @@ the row lists both.| snowflake | DB protocol | snowflake-connector-python | ➖ || stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |+| surveymonkey | HTTP | requests | ✅ || temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ || tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -210,7 +211,6 @@ doesn't conflict with concurrent PRs.- sharepoint- smartsheet- square-- surveymonkey- trello- twilio- twitter_adsdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 3458c8714ee3..856c029e7286 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -814,7 +814,8 @@ class SupabaseSourceConfig(config.Config):@config.configclass SurveyMonkeySourceConfig(config.Config):- pass+ access_token: str+ data_center: Literal["us", "eu", "ca"] = config.value(default="us")@config.configdiff --git a/posthog/temporal/data_imports/sources/surveymonkey/api_inventory.md b/posthog/temporal/data_imports/sources/surveymonkey/api_inventory.mdnew file mode 100644index 000000000000..1a6c14517fd9--- /dev/null+++ b/posthog/temporal/data_imports/sources/surveymonkey/api_inventory.md@@ -0,0 +1,49 @@+# SurveyMonkey API inventory++REST/JSON API at `https://api.surveymonkey.com/v3` (regional variants:+`https://api.eu.surveymonkey.com/v3`, `https://api.surveymonkey.ca/v3`).+Auth: `Authorization: bearer <access_token>` (private-app static token or OAuth2 bearer).+All list endpoints page with `page` / `per_page` and return+`{data: [...], page, per_page, total, links: {self, next, ...}}`. We follow `links.next`.++| Schema | Path | Grain | Primary key | Pagination | Incremental cursor | Partition (stable) |+| ------------------ | ------------------------------------------ | -------------- | ----------- | ------------- | ------------------------------------- | ------------------ |+| `surveys` | `/surveys` | account | `id` | `links.next` | `date_modified` (`start_modified_at`) | `date_created` |+| `survey_responses` | `/surveys/{survey_id}/responses/bulk` | fan-out/survey | `id` | `links.next` | `date_modified` / `date_created` | `date_created` |+| `survey_pages` | `/surveys/{survey_id}/pages` | fan-out/survey | `id` | `links.next` | full refresh | — |+| `survey_questions` | `/surveys/{survey_id}/details` (extracted) | fan-out/survey | `id` | none (1 call) | full refresh | — |+| `collectors` | `/surveys/{survey_id}/collectors` | fan-out/survey | `id` | `links.next` | full refresh | — |++Fan-out endpoints first enumerate every survey id via `/surveys`, then page the child+resource per survey. `survey_questions` is flattened from the nested `pages[].questions[]`+of `/surveys/{id}/details` to avoid a 2-level (`/pages/{page_id}/questions`) fan-out.+`survey_pages`/`collectors`/`survey_questions` rows are stamped with their `survey_id`+(and `page_id` for questions).++## Incremental sync++- `/surveys` documents `start_modified_at` (and `sort_by=date_modified`, `sort_order=ASC`),+ so `date_modified` is the only viable cursor (the sort enum is title/date_modified/+ num_responses and there is no `start_created_at` filter).+- `/surveys/{id}/responses/bulk` documents both `start_modified_at` and `start_created_at`,+ so either timestamp works as a cursor.++For fan-out incremental (`survey_responses`) the cursor is applied per-survey; the pipeline+watermark is the global max across surveys. `sort_mode="asc"` advances the watermark to the+running max after each page, which is correct on a completed sync. A hard crash without a+Redis resume could advance the watermark past unfetched older rows in a later survey — the+same edge case every incremental source carries — mitigated here by resumable state.++## Verification gaps++API behavior was confirmed against the public docs but **not** curl-verified against a live+account (no credentials available at implementation time). In particular:++- responses/bulk's `start_modified_at`/`start_created_at` filtering was confirmed from docs,+ not a future-date smoke test.+- responses/bulk sort ordering is undocumented, so we do **not** send `sort_by` there and+ rely on `links.next` for pagination.+- `collectors` is left full-refresh / unpartitioned because the list returns only+ `id`/`name`/`href` by default (no stable date field confirmed).++Revisit these once a live token is available; tighten incremental/sort behavior accordingly.diff --git a/posthog/temporal/data_imports/sources/surveymonkey/settings.py b/posthog/temporal/data_imports/sources/surveymonkey/settings.pynew file mode 100644index 000000000000..532fc13f5787--- /dev/null+++ b/posthog/temporal/data_imports/sources/surveymonkey/settings.py@@ -0,0 +1,101 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType++# SurveyMonkey caps `per_page` per endpoint (responses/bulk maxes out at 100). We use a+# single conservative value everywhere to avoid 400s, since daily call quotas are low and+# the docs disagree on per-endpoint maxima.+DEFAULT_PAGE_SIZE = 100+++def _datetime_incremental_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class SurveyMonkeyEndpointConfig:+ name: str+ # Path for top-level endpoints, or a `{survey_id}` template for fan-out endpoints.+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Fan-out endpoints first enumerate every survey, then page the child resource per survey.+ is_fanout: bool = False+ # `survey_questions` has no first-class list endpoint; questions are extracted from the+ # nested pages[].questions[] of `/surveys/{id}/details` (avoids a 2-level fan-out).+ extract_questions_from_details: bool = False+ default_incremental_field: Optional[str] = None+ # Partition on a STABLE field (date_created), never date_modified.+ partition_key: Optional[str] = None+ page_size: int = DEFAULT_PAGE_SIZE+ primary_key: str = "id"+ # The `sort_by` value to request when paging incrementally (must be a server-side enum).+ sort_by: Optional[str] = None+++SURVEYMONKEY_ENDPOINTS: dict[str, SurveyMonkeyEndpointConfig] = {+ "surveys": SurveyMonkeyEndpointConfig(+ name="surveys",+ path="/surveys",+ partition_key="date_created",+ default_incremental_field="date_modified",+ # `/surveys` only sorts by date_modified (the sort_by enum is title/date_modified/+ # num_responses) and only exposes a server-side start_modified_at filter, so+ # date_modified is the only viable cursor.+ sort_by="date_modified",+ incremental_fields=[+ _datetime_incremental_field("date_modified"),+ ],+ ),+ "survey_responses": SurveyMonkeyEndpointConfig(+ name="survey_responses",+ path="/surveys/{survey_id}/responses/bulk",+ is_fanout=True,+ partition_key="date_created",+ default_incremental_field="date_modified",+ # responses/bulk exposes both start_modified_at and start_created_at server-side+ # filters, so either timestamp works as a cursor.+ incremental_fields=[+ _datetime_incremental_field("date_modified"),+ _datetime_incremental_field("date_created"),+ ],+ ),+ "survey_pages": SurveyMonkeyEndpointConfig(+ name="survey_pages",+ path="/surveys/{survey_id}/pages",+ is_fanout=True,+ ),+ "survey_questions": SurveyMonkeyEndpointConfig(+ name="survey_questions",+ path="/surveys/{survey_id}/details",+ is_fanout=True,+ extract_questions_from_details=True,+ ),+ "collectors": SurveyMonkeyEndpointConfig(+ name="collectors",+ path="/surveys/{survey_id}/collectors",+ is_fanout=True,+ # The collectors list returns only id/name/href by default, so there is no stable+ # date field to partition on — full refresh, unpartitioned.+ ),+}++ENDPOINTS = tuple(SURVEYMONKEY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SURVEYMONKEY_ENDPOINTS.items()+}++# Datacenter -> API base URL. SurveyMonkey hosts regional datacenters; the correct host is+# returned as `access_url` during the OAuth token exchange, but private-app users know theirs.+DATA_CENTER_BASE_URLS: dict[str, str] = {+ "us": "https://api.surveymonkey.com/v3",+ "eu": "https://api.eu.surveymonkey.com/v3",+ "ca": "https://api.surveymonkey.ca/v3",+}+DEFAULT_DATA_CENTER = "us"diff --git a/posthog/temporal/data_imports/sources/surveymonkey/source.py b/posthog/temporal/data_imports/sources/surveymonkey/source.pyindex 84e63815fee2..c1ba10eada9a 100644--- a/posthog/temporal/data_imports/sources/surveymonkey/source.py+++ b/posthog/temporal/data_imports/sources/surveymonkey/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import SurveyMonkeySourceConfig+from posthog.temporal.data_imports.sources.surveymonkey.settings import (+ DATA_CENTER_BASE_URLS,+ DEFAULT_DATA_CENTER,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from posthog.temporal.data_imports.sources.surveymonkey.surveymonkey import (+ SurveyMonkeyResumeConfig,+ surveymonkey_source,+ validate_credentials as validate_surveymonkey_credentials,+)from products.data_warehouse.backend.types import ExternalDataSourceType+def _base_url_for(config: SurveyMonkeySourceConfig) -> str:+ data_center = getattr(config, "data_center", None) or DEFAULT_DATA_CENTER+ return DATA_CENTER_BASE_URLS.get(data_center, DATA_CENTER_BASE_URLS[DEFAULT_DATA_CENTER])++@SourceRegistry.register-class SurveyMonkeySource(SimpleSource[SurveyMonkeySourceConfig]):+class SurveyMonkeySource(ResumableSource[SurveyMonkeySourceConfig, SurveyMonkeyResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SURVEYMONKEY@@ -23,7 +47,95 @@ class SurveyMonkeySource(SimpleSource[SurveyMonkeySourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.SURVEY_MONKEY,label="SurveyMonkey",+ caption="""Enter a SurveyMonkey access token to pull your surveys, responses, and collectors into the PostHog Data warehouse.++Create a private app and generate an access token in the [SurveyMonkey developer dashboard](https://developer.surveymonkey.com/apps/).++Make sure to grant the following read scopes:+- `surveys_read`+- `responses_read_detail`+- `collectors_read`+""",iconPath="/static/services/surveymonkey.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/surveymonkey",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="data_center",+ label="Data center",+ required=True,+ defaultValue=DEFAULT_DATA_CENTER,+ options=[+ SourceFieldSelectConfigOption(label="US (api.surveymonkey.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (api.eu.surveymonkey.com)", value="eu"),+ SourceFieldSelectConfigOption(label="Canada (api.surveymonkey.ca)", value="ca"),+ ],+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your SurveyMonkey access token is invalid or expired. Please generate a new token and reconnect.",+ "403 Client Error: Forbidden for url": "Your SurveyMonkey access token is missing required scopes. Please grant `surveys_read`, `responses_read_detail`, and `collectors_read`, then reconnect.",+ }++ def get_schemas(+ self,+ config: SurveyMonkeySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+ for endpoint in list(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: SurveyMonkeySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_surveymonkey_credentials(config.access_token, _base_url_for(config))++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SurveyMonkeyResumeConfig]:+ return ResumableSourceManager[SurveyMonkeyResumeConfig](inputs, SurveyMonkeyResumeConfig)++ def source_for_pipeline(+ self,+ config: SurveyMonkeySourceConfig,+ resumable_source_manager: ResumableSourceManager[SurveyMonkeyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return surveymonkey_source(+ access_token=config.access_token,+ base_url=_base_url_for(config),+ 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+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/surveymonkey/surveymonkey.py b/posthog/temporal/data_imports/sources/surveymonkey/surveymonkey.pynew file mode 100644index 000000000000..395fcffa3c6d--- /dev/null+++ b/posthog/temporal/data_imports/sources/surveymonkey/surveymonkey.py@@ -0,0 +1,333 @@+import dataclasses+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime, time+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.surveymonkey.settings import (+ DEFAULT_PAGE_SIZE,+ SURVEYMONKEY_ENDPOINTS,+ SurveyMonkeyEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+++class SurveyMonkeyRetryableError(Exception):+ """Raised for 429 / 5xx responses so tenacity retries with backoff."""+++class SurveyMonkeyResumeConfig:+ # For the top-level `surveys` endpoint: the current list page URL to re-fetch on resume.+ # For fan-out endpoints: the current child-resource page URL within the survey at the head+ # of `remaining_survey_ids`.+ next_url: Optional[str] = None+ # Surveys not yet fully processed (fan-out only). The head of the list is the survey+ # currently being read, so a resume re-reads it and relies on primary-key merge to dedupe.+ remaining_survey_ids: Optional[list[str]] = None+++def _get_headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"bearer {access_token}",+ "Content-Type": "application/json",+ "Accept": "application/json",+ }+++def _format_incremental_value(value: Any) -> str:+ """SurveyMonkey expects `YYYY-MM-DDTHH:MM:SS` (UTC, no offset) for its date filters."""+ if isinstance(value, datetime):+ utc_value = value.astimezone(UTC) if value.tzinfo is not None else value+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S")+ if isinstance(value, date):+ return datetime.combine(value, time.min).strftime("%Y-%m-%dT%H:%M:%S")+ return str(value)+++def _cutoff_param_name(incremental_field: str | None, config: SurveyMonkeyEndpointConfig) -> str:+ """Map the chosen cursor field to its server-side filter param."""+ chosen = incremental_field or config.default_incremental_field+ if chosen == "date_created":+ return "start_created_at"+ return "start_modified_at"+++def _build_list_url(+ base_url: str,+ config: SurveyMonkeyEndpointConfig,+ cutoff: str | None,+ incremental_field: str | None,+ survey_id: str | None = None,+) -> str:+ path = config.path.format(survey_id=survey_id) if survey_id is not None else config.path+ params: dict[str, Any] = {"per_page": config.page_size}++ # Pull the stable/cursor dates and counts that aren't returned on the bare survey object.+ if config.name == "surveys":+ params["include"] = "date_created,date_modified,response_count,question_count"++ # Sort ascending on the cursor field so the pipeline's watermark advances monotonically and+ # offset pagination stays stable as new rows arrive. Only endpoints with a server-side sort+ # enum set `sort_by`; the rest page via the `links.next` cursor in the API's default order.+ if config.sort_by:+ params["sort_by"] = config.sort_by+ params["sort_order"] = "ASC"++ if cutoff:+ params[_cutoff_param_name(incremental_field, config)] = cutoff++ return f"{base_url}{path}?{urlencode(params)}"+++def validate_credentials(access_token: str, base_url: str) -> tuple[bool, str | None]:+ """Cheap probe against `/users/me` to confirm the token is genuine."""+ url = f"{base_url}/users/me"+ try:+ response = make_tracked_session().get(url, headers=_get_headers(access_token), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid SurveyMonkey access token"+ if response.status_code == 403:+ return False, "SurveyMonkey access token is missing required scopes"++ try:+ message = response.json().get("error", {}).get("message")+ except (ValueError, AttributeError):+ message = None+ return False, message or f"SurveyMonkey API returned status {response.status_code}"+++def _attach_survey_id(item: dict[str, Any], survey_id: str) -> dict[str, Any]:+ row = dict(item)+ row["survey_id"] = survey_id+ return row+++def _extract_questions(details: dict[str, Any], survey_id: str) -> list[dict[str, Any]]:+ """Flatten the nested pages[].questions[] of a `/surveys/{id}/details` payload."""+ rows: list[dict[str, Any]] = []+ for page in details.get("pages", []) or []:+ page_id = page.get("id")+ for question in page.get("questions", []) or []:+ row = dict(question)+ row["survey_id"] = survey_id+ row["page_id"] = page_id+ rows.append(row)+ return rows+++def get_rows(+ access_token: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SurveyMonkeyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SURVEYMONKEY_ENDPOINTS[endpoint]+ # One session reused across the whole sync (keeps TLS/TCP connections warm). urllib3 retries+ # are disabled so tenacity below is the single retry authority — otherwise the two layers+ # multiply request counts against SurveyMonkey's low daily call quota.+ session = make_tracked_session(headers=_get_headers(access_token), retry=Retry(total=0))++ cutoff = (+ _format_incremental_value(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )++ @retry(+ retry=retry_if_exception_type((SurveyMonkeyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_url: str) -> dict[str, Any]:+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise SurveyMonkeyRetryableError(+ f"SurveyMonkey API error (retryable): status={response.status_code}, url={page_url}"+ )++ if not response.ok:+ logger.error(f"SurveyMonkey API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.extract_questions_from_details:+ yield from _iter_questions(base_url, config, fetch_page, resumable_source_manager, resume, logger)+ elif config.is_fanout:+ yield from _iter_fanout(+ base_url, config, cutoff, incremental_field, fetch_page, resumable_source_manager, resume, logger+ )+ else:+ yield from _iter_top_level(+ base_url, config, cutoff, incremental_field, fetch_page, resumable_source_manager, resume+ )+++def _list_all_survey_ids(+ base_url: str,+ fetch_page: Callable[[str], dict[str, Any]],+) -> list[str]:+ """Enumerate every survey id by paging `/surveys` (ids only; no include/filter)."""+ survey_ids: list[str] = []+ url: str | None = f"{base_url}/surveys?{urlencode({'per_page': DEFAULT_PAGE_SIZE})}"+ while url:+ page = fetch_page(url)+ for item in page.get("data", []) or []:+ # Direct access: a survey without an id is a malformed response, and silently+ # skipping it would drop all of that survey's child records (pages, questions,+ # responses, collectors) with no trace. Fail loudly instead.+ survey_ids.append(str(item["id"]))+ url = page.get("links", {}).get("next")+ return survey_ids+++def _iter_top_level(+ base_url: str,+ config: SurveyMonkeyEndpointConfig,+ cutoff: str | None,+ incremental_field: str | None,+ fetch_page: Callable[[str], dict[str, Any]],+ manager: ResumableSourceManager[SurveyMonkeyResumeConfig],+ resume: SurveyMonkeyResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ url: str | None = (+ resume.next_url if resume and resume.next_url else _build_list_url(base_url, config, cutoff, incremental_field)+ )++ while url:+ page = fetch_page(url)+ items = page.get("data", []) or []+ next_url = page.get("links", {}).get("next")++ if items:+ yield items+ # Checkpoint the page we just yielded (not the next one) so a crash re-yields it+ # rather than skipping rows the pipeline may not have flushed yet.+ manager.save_state(SurveyMonkeyResumeConfig(next_url=url))++ url = next_url+++def _iter_fanout(+ base_url: str,+ config: SurveyMonkeyEndpointConfig,+ cutoff: str | None,+ incremental_field: str | None,+ fetch_page: Callable[[str], dict[str, Any]],+ manager: ResumableSourceManager[SurveyMonkeyResumeConfig],+ resume: SurveyMonkeyResumeConfig | None,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ if resume and resume.remaining_survey_ids is not None:+ remaining = list(resume.remaining_survey_ids)+ current_url = resume.next_url+ else:+ remaining = _list_all_survey_ids(base_url, fetch_page)+ current_url = None++ logger.debug(f"SurveyMonkey: fanning out {config.name} across {len(remaining)} surveys")++ while remaining:+ survey_id = remaining[0]+ if current_url is None:+ current_url = _build_list_url(base_url, config, cutoff, incremental_field, survey_id=survey_id)++ page = fetch_page(current_url)+ items = page.get("data", []) or []+ next_url = page.get("links", {}).get("next")++ if items:+ yield [_attach_survey_id(item, survey_id) for item in items]+ manager.save_state(SurveyMonkeyResumeConfig(next_url=current_url, remaining_survey_ids=remaining))++ if next_url:+ current_url = next_url+ else:+ remaining = remaining[1:]+ current_url = None+++def _iter_questions(+ base_url: str,+ config: SurveyMonkeyEndpointConfig,+ fetch_page: Callable[[str], dict[str, Any]],+ manager: ResumableSourceManager[SurveyMonkeyResumeConfig],+ resume: SurveyMonkeyResumeConfig | None,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ if resume and resume.remaining_survey_ids is not None:+ remaining = list(resume.remaining_survey_ids)+ else:+ remaining = _list_all_survey_ids(base_url, fetch_page)++ logger.debug(f"SurveyMonkey: extracting questions across {len(remaining)} surveys")++ while remaining:+ survey_id = remaining[0]+ details = fetch_page(f"{base_url}{config.path.format(survey_id=survey_id)}")+ questions = _extract_questions(details, survey_id)+ if questions:+ yield questions++ remaining = remaining[1:]+ # Checkpoint with the current survey already dropped — the `/details` call is idempotent,+ # so on resume we continue with the next survey.+ manager.save_state(SurveyMonkeyResumeConfig(remaining_survey_ids=remaining))+++def surveymonkey_source(+ access_token: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SurveyMonkeyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = SURVEYMONKEY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ access_token=access_token,+ base_url=base_url,+ 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,+ incremental_field=incremental_field,+ ),+ primary_keys=[config.primary_key],+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/surveymonkey/tests/test_surveymonkey.py b/posthog/temporal/data_imports/sources/surveymonkey/tests/test_surveymonkey.pynew file mode 100644index 000000000000..6a5e4bc80fe2--- /dev/null+++ b/posthog/temporal/data_imports/sources/surveymonkey/tests/test_surveymonkey.py@@ -0,0 +1,243 @@+from datetime import UTC, date, datetime+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.temporal.data_imports.sources.surveymonkey.settings import SURVEYMONKEY_ENDPOINTS+from posthog.temporal.data_imports.sources.surveymonkey.surveymonkey import (+ SurveyMonkeyResumeConfig,+ _attach_survey_id,+ _build_list_url,+ _cutoff_param_name,+ _extract_questions,+ _format_incremental_value,+ get_rows,+ validate_credentials,+)++BASE_URL = "https://api.surveymonkey.com/v3"++PATCH_TARGET = "posthog.temporal.data_imports.sources.surveymonkey.surveymonkey.make_tracked_session"+++class _FakeSession:+ """Returns queued JSON responses in call order and records the URLs requested."""++ def __init__(self, responses: list[tuple[int, dict[str, Any]]]):+ self._responses = list(responses)+ self.urls: list[str] = []++ def get(self, url: str, headers: dict[str, str] | None = None, timeout: int | None = None) -> MagicMock:+ self.urls.append(url)+ status, payload = self._responses.pop(0)+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ response.json.return_value = payload+ response.text = ""+ if status >= 400:+ response.raise_for_status.side_effect = Exception(f"{status} error")+ return response+++class _FakeManager:+ def __init__(self, state: SurveyMonkeyResumeConfig | None = None):+ self._state = state+ self.saved: list[SurveyMonkeyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SurveyMonkeyResumeConfig | None:+ return self._state++ def save_state(self, data: SurveyMonkeyResumeConfig) -> None:+ self.saved.append(data)+++def _patch_session(session: _FakeSession):+ return patch(PATCH_TARGET, lambda *args, **kwargs: session)+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00"),+ ("string_passthrough", "cursor-value", "cursor-value"),+ ]+ )+ def test_format_incremental_value(self, _name: str, value: object, expected: str) -> None:+ assert _format_incremental_value(value) == expected++ def test_no_offset_suffix(self) -> None:+ result = _format_incremental_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+ assert "+00:00" not in result and "Z" not in result+++class TestCutoffParamName:+ @parameterized.expand(+ [+ ("modified_default", "date_modified", "start_modified_at"),+ ("created", "date_created", "start_created_at"),+ ("none_falls_back_to_default", None, "start_modified_at"),+ ]+ )+ def test_cutoff_param_name(self, _name: str, incremental_field: str | None, expected: str) -> None:+ config = SURVEYMONKEY_ENDPOINTS["survey_responses"]+ assert _cutoff_param_name(incremental_field, config) == expected+++class TestBuildListUrl:+ def test_surveys_requests_include_sort_and_no_cutoff(self) -> None:+ url = _build_list_url(BASE_URL, SURVEYMONKEY_ENDPOINTS["surveys"], cutoff=None, incremental_field=None)+ assert url.startswith(f"{BASE_URL}/surveys?")+ assert "per_page=100" in url+ assert "include=" in url and "date_created" in url+ assert "sort_by=date_modified" in url+ assert "sort_order=ASC" in url+ assert "start_modified_at" not in url++ def test_surveys_applies_modified_cutoff(self) -> None:+ url = _build_list_url(+ BASE_URL, SURVEYMONKEY_ENDPOINTS["surveys"], cutoff="2026-01-01T00:00:00", incremental_field="date_modified"+ )+ assert "start_modified_at=2026-01-01T00%3A00%3A00" in url++ def test_responses_fanout_formats_survey_id_and_created_cutoff(self) -> None:+ url = _build_list_url(+ BASE_URL,+ SURVEYMONKEY_ENDPOINTS["survey_responses"],+ cutoff="2026-01-01T00:00:00",+ incremental_field="date_created",+ survey_id="42",+ )+ assert url.startswith(f"{BASE_URL}/surveys/42/responses/bulk?")+ assert "start_created_at=2026-01-01T00%3A00%3A00" in url+ # responses/bulk has no server-side sort enum, so we don't send sort_by.+ assert "sort_by" not in url+++class TestAttachSurveyId:+ def test_sets_survey_id(self) -> None:+ assert _attach_survey_id({"id": "p1"}, "10") == {"id": "p1", "survey_id": "10"}+++class TestExtractQuestions:+ def test_flattens_pages_and_questions_with_parents(self) -> None:+ details = {+ "id": "10",+ "pages": [+ {"id": "pg1", "questions": [{"id": "q1"}, {"id": "q2"}]},+ {"id": "pg2", "questions": [{"id": "q3"}]},+ {"id": "pg3", "questions": []},+ ],+ }+ rows = _extract_questions(details, "10")+ assert [r["id"] for r in rows] == ["q1", "q2", "q3"]+ assert all(r["survey_id"] == "10" for r in rows)+ assert rows[0]["page_id"] == "pg1"+ assert rows[2]["page_id"] == "pg2"++ def test_handles_missing_pages(self) -> None:+ assert _extract_questions({"id": "10"}, "10") == []+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, status: int, expected_ok: bool) -> None:+ session = _FakeSession([(status, {})])+ with _patch_session(session):+ ok, _error = validate_credentials("token", BASE_URL)+ assert ok is expected_ok+ assert session.urls == [f"{BASE_URL}/users/me"]+++class TestGetRowsTopLevel:+ def test_paginates_and_checkpoints_each_page(self) -> None:+ manager = _FakeManager()+ session = _FakeSession(+ [+ (200, {"data": [{"id": "1"}], "links": {"next": f"{BASE_URL}/surveys?page=2"}}),+ (200, {"data": [{"id": "2"}], "links": {}}),+ ]+ )+ with _patch_session(session):+ batches = list(+ get_rows("token", BASE_URL, "surveys", MagicMock(), manager) # type: ignore[arg-type]+ )++ assert [row["id"] for batch in batches for row in batch] == ["1", "2"]+ # First checkpoint points at the initial page URL, not the next one.+ assert manager.saved[0].next_url == session.urls[0]+ assert len(manager.saved) == 2++ def test_resumes_from_saved_url(self) -> None:+ manager = _FakeManager(SurveyMonkeyResumeConfig(next_url=f"{BASE_URL}/surveys?page=7"))+ session = _FakeSession([(200, {"data": [{"id": "99"}], "links": {}})])+ with _patch_session(session):+ batches = list(get_rows("token", BASE_URL, "surveys", MagicMock(), manager)) # type: ignore[arg-type]++ assert session.urls == [f"{BASE_URL}/surveys?page=7"]+ assert batches[0][0]["id"] == "99"+++class TestGetRowsFanout:+ def test_iterates_surveys_and_attaches_survey_id(self) -> None:+ manager = _FakeManager()+ session = _FakeSession(+ [+ (200, {"data": [{"id": "10"}, {"id": "20"}], "links": {}}), # survey list+ (200, {"data": [{"id": "p1"}], "links": {}}), # survey 10 pages+ (200, {"data": [{"id": "p2"}], "links": {}}), # survey 20 pages+ ]+ )+ with _patch_session(session):+ batches = list(+ get_rows("token", BASE_URL, "survey_pages", MagicMock(), manager) # type: ignore[arg-type]+ )++ rows = [row for batch in batches for row in batch]+ assert rows == [{"id": "p1", "survey_id": "10"}, {"id": "p2", "survey_id": "20"}]++ def test_resumes_remaining_surveys(self) -> None:+ manager = _FakeManager(+ SurveyMonkeyResumeConfig(next_url=f"{BASE_URL}/surveys/20/pages?per_page=100", remaining_survey_ids=["20"])+ )+ session = _FakeSession([(200, {"data": [{"id": "p2"}], "links": {}})])+ with _patch_session(session):+ batches = list(get_rows("token", BASE_URL, "survey_pages", MagicMock(), manager)) # type: ignore[arg-type]++ # No survey listing happens on resume; it goes straight to the saved child URL.+ assert session.urls == [f"{BASE_URL}/surveys/20/pages?per_page=100"]+ assert batches[0][0] == {"id": "p2", "survey_id": "20"}+++class TestGetRowsQuestions:+ def test_extracts_questions_per_survey(self) -> None:+ manager = _FakeManager()+ session = _FakeSession(+ [+ (200, {"data": [{"id": "10"}], "links": {}}), # survey list+ (200, {"id": "10", "pages": [{"id": "pg1", "questions": [{"id": "q1"}, {"id": "q2"}]}]}), # details+ ]+ )+ with _patch_session(session):+ batches = list(+ get_rows("token", BASE_URL, "survey_questions", MagicMock(), manager) # type: ignore[arg-type]+ )++ rows = [row for batch in batches for row in batch]+ assert [r["id"] for r in rows] == ["q1", "q2"]+ assert all(r["survey_id"] == "10" and r["page_id"] == "pg1" for r in rows)+ assert session.urls[-1] == f"{BASE_URL}/surveys/10/details"diff --git a/posthog/temporal/data_imports/sources/surveymonkey/tests/test_surveymonkey_source.py b/posthog/temporal/data_imports/sources/surveymonkey/tests/test_surveymonkey_source.pynew file mode 100644index 000000000000..fe310b3c538f--- /dev/null+++ b/posthog/temporal/data_imports/sources/surveymonkey/tests/test_surveymonkey_source.py@@ -0,0 +1,146 @@+from typing import Literal, cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import SurveyMonkeySourceConfig+from posthog.temporal.data_imports.sources.surveymonkey.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.surveymonkey.source import SurveyMonkeySource, _base_url_for+from posthog.temporal.data_imports.sources.surveymonkey.surveymonkey import SurveyMonkeyResumeConfig++from products.data_warehouse.backend.types import ExternalDataSourceType++SOURCE_PATCH = "posthog.temporal.data_imports.sources.surveymonkey.source"+++def _config(access_token: str = "token", data_center: Literal["us", "eu", "ca"] = "us") -> SurveyMonkeySourceConfig:+ return SurveyMonkeySourceConfig(access_token=access_token, data_center=data_center)+++class TestSurveyMonkeySourceType:+ def test_source_type(self) -> None:+ assert SurveyMonkeySource().source_type == ExternalDataSourceType.SURVEYMONKEY+++class TestSurveyMonkeySourceConfigFields:+ def test_exposes_access_token_and_data_center(self) -> None:+ cfg = SurveyMonkeySource().get_source_config++ names = {f.name for f in cfg.fields}+ assert names == {"access_token", "data_center"}++ token_field = next(f for f in cfg.fields if f.name == "access_token")+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.required is True+ assert token_field.secret is True++ dc_field = next(f for f in cfg.fields if f.name == "data_center")+ assert isinstance(dc_field, SourceFieldSelectConfig)+ assert dc_field.defaultValue == "us"+ assert {opt.value for opt in dc_field.options} == {"us", "eu", "ca"}++ def test_is_released_alpha(self) -> None:+ cfg = SurveyMonkeySource().get_source_config+ assert not cfg.unreleasedSource+ assert cfg.releaseStatus == ReleaseStatus.ALPHA+++class TestBaseUrlFor:+ @parameterized.expand(+ [+ ("us", "us", "https://api.surveymonkey.com/v3"),+ ("eu", "eu", "https://api.eu.surveymonkey.com/v3"),+ ("ca", "ca", "https://api.surveymonkey.ca/v3"),+ ]+ )+ def test_base_url_for(self, _name: str, data_center: Literal["us", "eu", "ca"], expected: str) -> None:+ assert _base_url_for(_config(data_center=data_center)) == expected+++class TestSurveyMonkeyGetSchemas:+ def test_exposes_all_endpoints(self) -> None:+ schemas = SurveyMonkeySource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_surveys_and_responses_support_incremental(self) -> None:+ schemas = SurveyMonkeySource().get_schemas(_config(), team_id=1)+ incremental = {s.name for s in schemas if s.supports_incremental}+ assert incremental == {"surveys", "survey_responses"}++ def test_full_refresh_endpoints_have_no_incremental_fields(self) -> None:+ schemas = {s.name: s for s in SurveyMonkeySource().get_schemas(_config(), team_id=1)}+ for name in ("survey_pages", "survey_questions", "collectors"):+ assert schemas[name].incremental_fields == []+ assert schemas[name].supports_incremental is False++ def test_filters_by_names(self) -> None:+ schemas = SurveyMonkeySource().get_schemas(_config(), team_id=1, names=["surveys", "collectors"])+ assert {s.name for s in schemas} == {"surveys", "collectors"}+++class TestSurveyMonkeyValidateCredentials:+ @patch(f"{SOURCE_PATCH}.validate_surveymonkey_credentials")+ def test_delegates_with_resolved_base_url(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (True, None)++ ok, error = SurveyMonkeySource().validate_credentials(_config(data_center="eu"), team_id=1)++ assert ok is True and error is None+ mock_validate.assert_called_once_with("token", "https://api.eu.surveymonkey.com/v3")+++class TestSurveyMonkeyResumableManager:+ def test_returns_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = SurveyMonkeySource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SurveyMonkeyResumeConfig+++class TestSurveyMonkeySourceForPipeline:+ def _inputs(self, schema_name: str = "surveys") -> MagicMock:+ inputs = MagicMock()+ inputs.schema_name = schema_name+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = None+ inputs.incremental_field = None+ return inputs++ def test_passes_token_base_url_and_endpoint(self) -> None:+ sentinel = cast(SourceResponse, object())+ with patch(f"{SOURCE_PATCH}.surveymonkey_source") as mock_source:+ mock_source.return_value = sentinel+ result = SurveyMonkeySource().source_for_pipeline(+ _config(data_center="ca"), MagicMock(), self._inputs("survey_responses")+ )++ assert result is sentinel+ kwargs = mock_source.call_args.kwargs+ assert kwargs["access_token"] == "token"+ assert kwargs["base_url"] == "https://api.surveymonkey.ca/v3"+ assert kwargs["endpoint"] == "survey_responses"++ def test_surveys_response_partitions_by_date_created(self) -> None:+ response = SurveyMonkeySource().source_for_pipeline(_config(), MagicMock(), self._inputs("surveys"))+ assert response.name == "surveys"+ assert response.primary_keys == ["id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["date_created"]+ assert response.sort_mode == "asc"++ def test_questions_response_is_unpartitioned(self) -> None:+ response = SurveyMonkeySource().source_for_pipeline(_config(), MagicMock(), self._inputs("survey_questions"))+ assert response.partition_mode is None+ assert response.partition_keys is None+++class TestSurveyMonkeyNonRetryableErrors:+ def test_marks_auth_errors_non_retryable(self) -> None:+ errors = SurveyMonkeySource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)