: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 surveysparrow import source (#69380)
Tom Owersf1505ce14748
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 52c9f378125d..8701fad6e10b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -331,6 +331,7 @@ the row lists both.| stripe | HTTP (vendor SDK) + Webhook | stripe (StripeClient + RequestsClient) + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ || surveymonkey | HTTP | requests | ✅ |+| surveysparrow | HTTP | requests | ✅ || svix | HTTP | requests | ✅ || taboola | HTTP | requests | ✅ || tavus | HTTP | requests | ✅ |@@ -709,7 +710,6 @@ doesn't conflict with concurrent PRs.- streamlabs- superwall- surveymonkey-- surveysparrow- survicate- svix- systemediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 21945e8fd28c..b4b774847e6f 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@@ -3315,7 +3315,8 @@ class SurveyMonkeySourceConfig(config.Config):@config.configclass SurveySparrowSourceConfig(config.Config):- pass+ access_token: str+ data_center: Literal["us", "eu", "ap", "me", "uk", "ap-sy", "ca"] = config.value(default="us")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/canonical_descriptions.pynew file mode 100644index 000000000000..b52a198d684b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/canonical_descriptions.py@@ -0,0 +1,66 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "surveys": {+ "description": "A survey in the SurveySparrow account, such as a conversational form, NPS, CSAT, or CES survey.",+ "docs_url": "https://developers.surveysparrow.com/rest-apis/survey",+ "columns": {+ "id": "Unique identifier for the survey.",+ "name": "Name of the survey.",+ "archived": "Whether the survey has been archived.",+ "survey_type": "Type of the survey (e.g. Conversational, ClassicForm, NPS, CES, CSAT).",+ "created_at": "Timestamp when the survey was created.",+ "updated_at": "Timestamp when the survey was last updated.",+ "survey_folder_id": "Identifier of the folder the survey belongs to.",+ "survey_folder_name": "Name of the folder the survey belongs to.",+ },+ },+ "responses": {+ "description": "A completed submission to a survey, including the answers given to each question.",+ "docs_url": "https://developers.surveysparrow.com/rest-apis/response",+ "columns": {+ "id": "Identifier for the response within its survey.",+ "survey_id": "Identifier of the survey the response belongs to.",+ "contact_id": "Identifier of the contact who submitted the response, if known.",+ "completed": "Submission status of the response.",+ "completed_time": "Timestamp when the response was submitted.",+ "channel_id": "Identifier of the share channel the response came through.",+ "channel": "Share channel the response came through (name, type, and status).",+ "language": "Language the response was submitted in.",+ "answers": "Answers given to each question in the survey.",+ },+ },+ "questions": {+ "description": "A question belonging to a survey.",+ "docs_url": "https://developers.surveysparrow.com/rest-apis/questions",+ "columns": {+ "id": "Unique identifier for the question.",+ "survey_id": "Identifier of the survey the question belongs to.",+ "section_id": "Identifier of the survey section the question belongs to.",+ "type": "Question type (e.g. TextInput, OpinionScale, Rating).",+ "position": "Position of the question within the survey.",+ "hasDisplayLogic": "Whether the question has display logic attached.",+ "properties": "Additional configuration of the question.",+ "account_id": "Identifier of the SurveySparrow account.",+ "parent_question_id": "Identifier of the parent question, if this is a follow-up.",+ },+ },+ "contacts": {+ "description": "A contact stored in the SurveySparrow audience, used to share surveys and track who responded.",+ "docs_url": "https://developers.surveysparrow.com/rest-apis/contacts",+ "columns": {+ "id": "Unique identifier for the contact.",+ },+ },+ "contact_lists": {+ "description": "A named list grouping contacts for survey distribution.",+ "docs_url": "https://developers.surveysparrow.com/rest-apis/contact-lists",+ "columns": {+ "id": "Unique identifier for the contact list.",+ "name": "Name of the contact list.",+ "description": "Description of the contact list.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/settings.pynew file mode 100644index 000000000000..789c7132c37e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/settings.py@@ -0,0 +1,106 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# SurveySparrow caps `limit` per endpoint: 100 on surveys/questions, 200 on responses, 50 on+# contacts and contact_lists. Each endpoint config carries its own maximum to minimise round+# trips without 400s.+DEFAULT_PAGE_SIZE = 100++COMPLETED_TIME_INCREMENTAL: IncrementalField = {+ "label": "completed_time",+ "type": IncrementalFieldType.DateTime,+ "field": "completed_time",+ "field_type": IncrementalFieldType.DateTime,+}+++@dataclass+class SurveySparrowEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Fan-out endpoints first enumerate every survey, then page the child resource per survey+ # (SurveySparrow requires `survey_id` as a query param on /v3/responses and /v3/questions).+ is_fanout: bool = False+ default_incremental_field: Optional[str] = None+ # Server-side filter param the incremental cutoff maps to.+ cutoff_param: Optional[str] = None+ # Partition on a STABLE field (created_at / completed_time), never updated_at.+ partition_key: Optional[str] = None+ page_size: int = DEFAULT_PAGE_SIZE+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Static query params sent on every request (e.g. a server-side sort on the cursor field).+ extra_params: dict[str, str] = field(default_factory=dict)+++SURVEYSPARROW_ENDPOINTS: dict[str, SurveySparrowEndpointConfig] = {+ # Full refresh: /v3/surveys documents created/updated date filters but no sort param, so+ # neither pagination stability nor watermark ordering can be guaranteed for an incremental+ # cursor. The table is small, so a full refresh per sync is cheap.+ "surveys": SurveySparrowEndpointConfig(+ name="surveys",+ path="/v3/surveys",+ partition_key="created_at",+ page_size=100,+ ),+ "responses": SurveySparrowEndpointConfig(+ name="responses",+ path="/v3/responses",+ is_fanout=True,+ partition_key="completed_time",+ default_incremental_field="completed_time",+ cutoff_param="date.gte",+ incremental_fields=[COMPLETED_TIME_INCREMENTAL],+ page_size=200,+ # A response id is only documented as unique within its survey, and the table+ # aggregates responses across every survey, so the survey id is part of the key.+ primary_keys=["survey_id", "id"],+ # Only completed responses: partial submissions have no `completed_time`, which is both+ # the incremental cursor and the partition key. Sort ascending on the cursor field so+ # the pipeline's watermark advances monotonically and page-number pagination stays+ # stable as new responses arrive.+ extra_params={"state": "completed", "order_by": "completedTime", "order": "ASC"},+ ),+ "questions": SurveySparrowEndpointConfig(+ name="questions",+ path="/v3/questions",+ is_fanout=True,+ page_size=100,+ primary_keys=["survey_id", "id"],+ ),+ "contacts": SurveySparrowEndpointConfig(+ name="contacts",+ path="/v3/contacts",+ # The contact endpoints cap `limit` at 50, unlike surveys/questions/responses.+ page_size=50,+ ),+ "contact_lists": SurveySparrowEndpointConfig(+ name="contact_lists",+ path="/v3/contact_lists",+ # /v3/contact_lists caps `limit` at 50, same as /v3/contacts.+ page_size=50,+ ),+}++ENDPOINTS = tuple(SURVEYSPARROW_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SURVEYSPARROW_ENDPOINTS.items()+}++# Data center -> API base URL. SurveySparrow assigns each account to a regional data center;+# tokens are only valid against their own region's host. Every host below responds on+# /v3/surveys (verified by probe), including the Sydney host, which the docs list with an+# `-app` suffix instead of `-api`.+DATA_CENTER_BASE_URLS: dict[str, str] = {+ "us": "https://api.surveysparrow.com",+ "eu": "https://eu-api.surveysparrow.com",+ "ap": "https://ap-api.surveysparrow.com",+ "me": "https://me-api.surveysparrow.com",+ "uk": "https://eu-ln-api.surveysparrow.com",+ "ap-sy": "https://ap-sy-app.surveysparrow.com",+ "ca": "https://ca-api.surveysparrow.com",+}+DEFAULT_DATA_CENTER = "us"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/source.pyindex 46f4676d7cc7..40613cd65970 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/source.py@@ -1,19 +1,52 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SurveySparrowSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.settings import (+ DATA_CENTER_BASE_URLS,+ DEFAULT_DATA_CENTER,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SURVEYSPARROW_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.surveysparrow import (+ SurveySparrowResumeConfig,+ surveysparrow_source,+ validate_credentials as validate_surveysparrow_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _base_url_for(config: SurveySparrowSourceConfig) -> 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 SurveySparrowSource(SimpleSource[SurveySparrowSourceConfig]):+class SurveySparrowSource(ResumableSource[SurveySparrowSourceConfig, SurveySparrowResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SURVEYSPARROW@@ -24,7 +57,107 @@ class SurveySparrowSource(SimpleSource[SurveySparrowSourceConfig]):name=SchemaExternalDataSourceType.SURVEY_SPARROW,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="SurveySparrow",+ caption="""Enter a SurveySparrow access token to pull your surveys, responses, questions, and contacts into the PostHog Data warehouse.++Create a private app and generate an access token under **Settings → Apps & Integrations** in [SurveySparrow](https://surveysparrow.com). The token is displayed only once, so copy it when it's created.++Pick the data center your SurveySparrow account is hosted in — tokens are only valid against their own region's API host.+""",iconPath="/static/services/surveysparrow.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/surveysparrow",+ 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.surveysparrow.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (eu-api.surveysparrow.com)", value="eu"),+ SourceFieldSelectConfigOption(label="Asia-Pacific (ap-api.surveysparrow.com)", value="ap"),+ SourceFieldSelectConfigOption(label="Middle East (me-api.surveysparrow.com)", value="me"),+ SourceFieldSelectConfigOption(label="UK (eu-ln-api.surveysparrow.com)", value="uk"),+ SourceFieldSelectConfigOption(label="Sydney (ap-sy-app.surveysparrow.com)", value="ap-sy"),+ SourceFieldSelectConfigOption(label="Canada (ca-api.surveysparrow.com)", value="ca"),+ ],+ ),+ ],+ ),unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.canonical_descriptions import ( # noqa: PLC0415 — keeps the descriptions dict off the import path+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your SurveySparrow access token is invalid or has been revoked. Generate a new token under Settings → Apps & Integrations and check the data center matches your account, then reconnect.",+ "403 Client Error: Forbidden for url": "Your SurveySparrow access token is missing the required scopes. Grant read access for the resources you want to sync, then reconnect.",+ }++ def get_schemas(+ self,+ config: SurveySparrowSourceConfig,+ 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 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: SurveySparrowSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The access token is account-wide, so a single probe validates access for every schema.+ return validate_surveysparrow_credentials(config.access_token, _base_url_for(config))++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SurveySparrowResumeConfig]:+ return ResumableSourceManager[SurveySparrowResumeConfig](inputs, SurveySparrowResumeConfig)++ def source_for_pipeline(+ self,+ config: SurveySparrowSourceConfig,+ resumable_source_manager: ResumableSourceManager[SurveySparrowResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in SURVEYSPARROW_ENDPOINTS:+ raise ValueError(f"Unknown SurveySparrow schema '{inputs.schema_name}'")++ return surveysparrow_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,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/surveysparrow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/surveysparrow.pynew file mode 100644index 000000000000..a5c01d31c3df--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/surveysparrow.py@@ -0,0 +1,259 @@+import dataclasses+from collections.abc import Callable, Iterator+from datetime import date, datetime+from typing import Any, Optional++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 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.surveysparrow.settings import (+ SURVEYSPARROW_ENDPOINTS,+ SurveySparrowEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# Page size used when enumerating survey ids for fan-out endpoints (/v3/surveys caps at 100).+SURVEY_LIST_PAGE_SIZE = 100+++class SurveySparrowRetryableError(Exception):+ """Raised for 429 / 5xx responses so tenacity retries with backoff."""+++class SurveySparrowResumeConfig:+ # Page currently being fetched. Checkpointed after its rows are yielded, so a resume+ # re-fetches (and re-yields) that page rather than skipping rows the pipeline may not have+ # flushed yet; merge dedupes on the primary key.+ page: int = 1+ # Surveys not yet fully processed (fan-out only). The head of the list is the survey+ # currently being read at `page`.+ remaining_survey_ids: Optional[list[int]] = None+++def _get_headers(access_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {access_token}",+ "Accept": "application/json",+ }+++def _format_cutoff(value: Any) -> str:+ """Format the incremental watermark for SurveySparrow's date filters.++ The docs only specify `YYYY-MM-DD` dates for these filters, so the watermark is floored to+ its day: each incremental sync re-fetches up to one day of overlap, which merge dedupes.+ """+ if isinstance(value, datetime):+ return value.strftime("%Y-%m-%d")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%d")+ return str(value)+++def _build_params(+ config: SurveySparrowEndpointConfig,+ page: int,+ cutoff: str | None = None,+ survey_id: int | None = None,+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": config.page_size, "page": page, **config.extra_params}+ if survey_id is not None:+ params["survey_id"] = survey_id+ if cutoff and config.cutoff_param:+ params[config.cutoff_param] = cutoff+ return params+++def _attach_survey_id(item: dict[str, Any], survey_id: int) -> dict[str, Any]:+ row = dict(item)+ # Rows already carry survey_id per the docs, but the composite primary key must never be+ # null, so stamp it from the fan-out loop regardless.+ row["survey_id"] = survey_id+ return row+++def validate_credentials(access_token: str, base_url: str) -> tuple[bool, str | None]:+ """Cheap probe against `/v3/surveys` to confirm the token is genuine for this data center."""+ session = make_tracked_session(headers=_get_headers(access_token), redact_values=(access_token,))+ try:+ response = session.get(f"{base_url}/v3/surveys", params={"limit": 1}, timeout=15)+ except requests.exceptions.RequestException as e:+ return False, f"Could not connect to SurveySparrow: {e}"++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return (+ False,+ "Invalid SurveySparrow access token. Check the token and that the data center matches your account.",+ )+ if response.status_code == 403:+ return False, "Your SurveySparrow access token is missing the required scopes."++ return False, f"SurveySparrow API returned status {response.status_code}"+++def get_rows(+ access_token: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SurveySparrowResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = SURVEYSPARROW_ENDPOINTS[endpoint]+ # One session reused across the whole sync. urllib3 retries are disabled so tenacity below+ # is the single retry authority.+ session = make_tracked_session(+ headers=_get_headers(access_token), retry=Retry(total=0), redact_values=(access_token,)+ )++ cutoff = (+ _format_cutoff(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )++ @retry(+ retry=retry_if_exception_type((SurveySparrowRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(path: str, params: dict[str, Any]) -> tuple[list[dict[str, Any]], bool]:+ response = session.get(f"{base_url}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise SurveySparrowRetryableError(+ f"SurveySparrow API error (retryable): status={response.status_code}, path={path}"+ )++ if not response.ok:+ logger.error(f"SurveySparrow API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ payload = response.json()+ if not isinstance(payload, dict) or not isinstance(payload.get("data"), list):+ raise SurveySparrowRetryableError(f"SurveySparrow returned an unexpected payload for {path}")++ # Some list endpoints (e.g. /v3/contact_lists) don't document has_next_page; a missing+ # flag means the page is the last one.+ return payload["data"], bool(payload.get("has_next_page"))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.is_fanout:+ yield from _iter_fanout(config, cutoff, fetch_page, resumable_source_manager, resume, logger)+ else:+ yield from _iter_top_level(config, cutoff, fetch_page, resumable_source_manager, resume)+++FetchPage = Callable[[str, dict[str, Any]], tuple[list[dict[str, Any]], bool]]+++def _iter_top_level(+ config: SurveySparrowEndpointConfig,+ cutoff: str | None,+ fetch_page: FetchPage,+ manager: ResumableSourceManager[SurveySparrowResumeConfig],+ resume: SurveySparrowResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ page = resume.page if resume else 1++ while True:+ items, has_next = fetch_page(config.path, _build_params(config, page, cutoff))+ if items:+ yield items+ manager.save_state(SurveySparrowResumeConfig(page=page))++ # An empty page also terminates defensively so a stale flag can never loop forever.+ if not has_next or not items:+ break+ page += 1+++def _list_all_survey_ids(fetch_page: FetchPage) -> list[int]:+ """Enumerate every survey id by paging /v3/surveys (fan-out parents)."""+ survey_ids: list[int] = []+ page = 1+ while True:+ items, has_next = fetch_page("/v3/surveys", {"limit": SURVEY_LIST_PAGE_SIZE, "page": page})+ for item in items:+ # Direct access: a survey without an id is a malformed response, and silently+ # skipping it would drop all of that survey's child rows with no trace.+ survey_ids.append(int(item["id"]))+ if not has_next or not items:+ return survey_ids+ page += 1+++def _iter_fanout(+ config: SurveySparrowEndpointConfig,+ cutoff: str | None,+ fetch_page: FetchPage,+ manager: ResumableSourceManager[SurveySparrowResumeConfig],+ resume: SurveySparrowResumeConfig | None,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ if resume and resume.remaining_survey_ids is not None:+ remaining = list(resume.remaining_survey_ids)+ page = resume.page+ else:+ remaining = _list_all_survey_ids(fetch_page)+ page = 1++ logger.debug(f"SurveySparrow: fanning out {config.name} across {len(remaining)} surveys")++ while remaining:+ survey_id = remaining[0]+ items, has_next = fetch_page(config.path, _build_params(config, page, cutoff, survey_id=survey_id))++ if items:+ yield [_attach_survey_id(item, survey_id) for item in items]+ manager.save_state(SurveySparrowResumeConfig(page=page, remaining_survey_ids=remaining))++ if has_next and items:+ page += 1+ else:+ remaining = remaining[1:]+ page = 1+++def surveysparrow_source(+ access_token: str,+ base_url: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SurveySparrowResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SURVEYSPARROW_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,+ ),+ primary_keys=config.primary_keys,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/tests/test_surveysparrow.py b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/tests/test_surveysparrow.pynew file mode 100644index 000000000000..65ce6727589e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/tests/test_surveysparrow.py@@ -0,0 +1,256 @@+from datetime import UTC, date, datetime+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.settings import (+ SURVEYSPARROW_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.surveysparrow import (+ SurveySparrowResumeConfig,+ _attach_survey_id,+ _build_params,+ _format_cutoff,+ get_rows,+ validate_credentials,+)++BASE_URL = "https://api.surveysparrow.com"++PATCH_TARGET = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.surveysparrow.make_tracked_session"+)+++class _FakeSession:+ """Returns queued JSON responses in call order and records each request."""++ def __init__(self, responses: list[tuple[int, dict[str, Any]]]):+ self._responses = list(responses)+ self.requests: list[tuple[str, dict[str, Any] | None]] = []++ def get(self, url: str, params: dict[str, Any] | None = None, timeout: int | None = None) -> MagicMock:+ self.requests.append((url, params))+ 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: SurveySparrowResumeConfig | None = None):+ self._state = state+ self.saved: list[SurveySparrowResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SurveySparrowResumeConfig | None:+ return self._state++ def save_state(self, data: SurveySparrowResumeConfig) -> None:+ self.saved.append(data)+++def _patch_session(session: _FakeSession):+ return patch(PATCH_TARGET, lambda *args, **kwargs: session)+++class TestFormatCutoff:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04"),+ ("date_value", date(2026, 3, 4), "2026-03-04"),+ ("string_passthrough", "2026-03-04", "2026-03-04"),+ ]+ )+ def test_floors_watermark_to_day(self, _name: str, value: object, expected: str) -> None:+ assert _format_cutoff(value) == expected+++class TestBuildParams:+ def test_responses_carry_survey_id_cutoff_and_completed_sort(self) -> None:+ params = _build_params(SURVEYSPARROW_ENDPOINTS["responses"], page=3, cutoff="2026-01-01", survey_id=42)+ assert params["survey_id"] == 42+ assert params["date.gte"] == "2026-01-01"+ assert params["page"] == 3+ assert params["limit"] == 200+ assert params["state"] == "completed"+ assert params["order_by"] == "completedTime"+ assert params["order"] == "ASC"++ def test_cutoff_dropped_on_endpoints_without_server_filter(self) -> None:+ params = _build_params(SURVEYSPARROW_ENDPOINTS["questions"], page=1, cutoff="2026-01-01", survey_id=42)+ assert "date.gte" not in params+ assert params["survey_id"] == 42++ def test_surveys_have_no_survey_id_or_extra_params(self) -> None:+ params = _build_params(SURVEYSPARROW_ENDPOINTS["surveys"], page=1)+ assert params == {"limit": 100, "page": 1}+++class TestAttachSurveyId:+ def test_stamps_survey_id_for_composite_key(self) -> None:+ assert _attach_survey_id({"id": 7}, 42) == {"id": 7, "survey_id": 42}+++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.requests[0][0] == f"{BASE_URL}/v3/surveys"+++class TestGetRowsTopLevel:+ def test_paginates_and_checkpoints_each_page(self) -> None:+ manager = _FakeManager()+ session = _FakeSession(+ [+ (200, {"has_next_page": True, "data": [{"id": 1}]}),+ (200, {"has_next_page": False, "data": [{"id": 2}]}),+ ]+ )+ 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]+ assert [params["page"] for _url, params in session.requests if params] == [1, 2]+ # Checkpoints point at the page just yielded, so a resume re-fetches (not skips) it.+ assert [state.page for state in manager.saved] == [1, 2]++ def test_missing_has_next_page_terminates(self) -> None:+ manager = _FakeManager()+ session = _FakeSession([(200, {"data": [{"id": 1}]})])+ with _patch_session(session):+ batches = list(get_rows("token", BASE_URL, "contact_lists", MagicMock(), manager)) # type: ignore[arg-type]++ assert len(session.requests) == 1+ assert batches == [[{"id": 1}]]++ def test_empty_page_terminates_despite_stale_flag(self) -> None:+ manager = _FakeManager()+ session = _FakeSession([(200, {"has_next_page": True, "data": []})])+ with _patch_session(session):+ batches = list(get_rows("token", BASE_URL, "surveys", MagicMock(), manager)) # type: ignore[arg-type]++ assert batches == []+ assert len(session.requests) == 1++ def test_resumes_from_saved_page(self) -> None:+ manager = _FakeManager(SurveySparrowResumeConfig(page=7))+ session = _FakeSession([(200, {"has_next_page": False, "data": [{"id": 99}]})])+ with _patch_session(session):+ batches = list(get_rows("token", BASE_URL, "surveys", MagicMock(), manager)) # type: ignore[arg-type]++ assert session.requests[0][1] is not None+ assert session.requests[0][1]["page"] == 7+ assert batches[0][0]["id"] == 99+++class TestGetRowsFanout:+ def test_iterates_surveys_and_stamps_survey_id(self) -> None:+ manager = _FakeManager()+ session = _FakeSession(+ [+ (200, {"has_next_page": False, "data": [{"id": 10}, {"id": 20}]}), # survey list+ (200, {"has_next_page": False, "data": [{"id": 1}]}), # survey 10 responses+ (200, {"has_next_page": False, "data": [{"id": 2}]}), # survey 20 responses+ ]+ )+ with _patch_session(session):+ batches = list(get_rows("token", BASE_URL, "responses", MagicMock(), manager)) # type: ignore[arg-type]++ rows = [row for batch in batches for row in batch]+ assert rows == [{"id": 1, "survey_id": 10}, {"id": 2, "survey_id": 20}]+ child_requests = session.requests[1:]+ assert [params["survey_id"] for _url, params in child_requests if params] == [10, 20]++ def test_pages_within_survey_then_advances_to_next(self) -> None:+ manager = _FakeManager()+ session = _FakeSession(+ [+ (200, {"has_next_page": False, "data": [{"id": 10}, {"id": 20}]}), # survey list+ (200, {"has_next_page": True, "data": [{"id": 1}]}), # survey 10 page 1+ (200, {"has_next_page": False, "data": [{"id": 2}]}), # survey 10 page 2+ (200, {"has_next_page": False, "data": [{"id": 3}]}), # survey 20 page 1+ ]+ )+ with _patch_session(session):+ list(get_rows("token", BASE_URL, "responses", MagicMock(), manager)) # type: ignore[arg-type]++ child_params = [params for _url, params in session.requests[1:] if params]+ assert [(p["survey_id"], p["page"]) for p in child_params] == [(10, 1), (10, 2), (20, 1)]++ def test_incremental_cutoff_applied_to_children_but_not_survey_enumeration(self) -> None:+ manager = _FakeManager()+ session = _FakeSession(+ [+ (200, {"has_next_page": False, "data": [{"id": 10}]}),+ (200, {"has_next_page": False, "data": [{"id": 1}]}),+ ]+ )+ with _patch_session(session):+ list(+ get_rows(+ "token",+ BASE_URL,+ "responses",+ MagicMock(),+ manager, # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),+ )+ )++ survey_list_params = session.requests[0][1]+ child_params = session.requests[1][1]+ assert survey_list_params is not None and "date.gte" not in survey_list_params+ assert child_params is not None and child_params["date.gte"] == "2026-01-02"++ def test_resumes_remaining_surveys_without_relisting(self) -> None:+ manager = _FakeManager(SurveySparrowResumeConfig(page=4, remaining_survey_ids=[20]))+ session = _FakeSession([(200, {"has_next_page": False, "data": [{"id": 2}]})])+ with _patch_session(session):+ batches = list(get_rows("token", BASE_URL, "responses", MagicMock(), manager)) # type: ignore[arg-type]++ # No survey enumeration on resume; it goes straight to the saved survey and page.+ assert len(session.requests) == 1+ url, params = session.requests[0]+ assert url == f"{BASE_URL}/v3/responses"+ assert params is not None and params["survey_id"] == 20 and params["page"] == 4+ assert batches[0][0] == {"id": 2, "survey_id": 20}++ def test_checkpoints_current_survey_and_page(self) -> None:+ manager = _FakeManager()+ session = _FakeSession(+ [+ (200, {"has_next_page": False, "data": [{"id": 10}, {"id": 20}]}),+ (200, {"has_next_page": False, "data": [{"id": 1}]}),+ (200, {"has_next_page": False, "data": [{"id": 2}]}),+ ]+ )+ with _patch_session(session):+ list(get_rows("token", BASE_URL, "responses", MagicMock(), manager)) # type: ignore[arg-type]++ assert [(state.remaining_survey_ids, state.page) for state in manager.saved] == [+ ([10, 20], 1),+ ([20], 1),+ ]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/tests/test_surveysparrow_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/tests/test_surveysparrow_source.pynew file mode 100644index 000000000000..db2525196c06--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/surveysparrow/tests/test_surveysparrow_source.py@@ -0,0 +1,156 @@+from typing import cast++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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 SurveySparrowSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.source import (+ SurveySparrowSource,+ _base_url_for,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.surveysparrow import (+ SurveySparrowResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++SOURCE_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.surveysparrow.source"+++def _config(access_token: str = "token", data_center: str = "us") -> SurveySparrowSourceConfig:+ return SurveySparrowSourceConfig(access_token=access_token, data_center=data_center) # type: ignore[arg-type]+++class TestSurveySparrowSourceType:+ def test_source_type(self) -> None:+ assert SurveySparrowSource().source_type == ExternalDataSourceType.SURVEYSPARROW+++class TestSurveySparrowSourceConfigFields:+ def test_exposes_access_token_and_data_center(self) -> None:+ cfg = SurveySparrowSource().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", "ap", "me", "uk", "ap-sy", "ca"}++ def test_release_status_is_alpha(self) -> None:+ assert SurveySparrowSource().get_source_config.releaseStatus == ReleaseStatus.ALPHA+++class TestBaseUrlFor:+ @parameterized.expand(+ [+ ("us", "us", "https://api.surveysparrow.com"),+ ("eu", "eu", "https://eu-api.surveysparrow.com"),+ ("ap", "ap", "https://ap-api.surveysparrow.com"),+ ("me", "me", "https://me-api.surveysparrow.com"),+ ("uk", "uk", "https://eu-ln-api.surveysparrow.com"),+ ("sydney", "ap-sy", "https://ap-sy-app.surveysparrow.com"),+ ("ca", "ca", "https://ca-api.surveysparrow.com"),+ ]+ )+ def test_base_url_for(self, _name: str, data_center: str, expected: str) -> None:+ assert _base_url_for(_config(data_center=data_center)) == expected++ def test_unknown_data_center_falls_back_to_us(self) -> None:+ assert _base_url_for(_config(data_center="nope")) == "https://api.surveysparrow.com"+++class TestSurveySparrowGetSchemas:+ def test_exposes_all_endpoints(self) -> None:+ schemas = SurveySparrowSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_responses_support_incremental(self) -> None:+ schemas = SurveySparrowSource().get_schemas(_config(), team_id=1)+ incremental = {s.name for s in schemas if s.supports_incremental}+ assert incremental == {"responses"}++ def test_filters_by_names(self) -> None:+ schemas = SurveySparrowSource().get_schemas(_config(), team_id=1, names=["surveys", "contacts"])+ assert {s.name for s in schemas} == {"surveys", "contacts"}+++class TestSurveySparrowValidateCredentials:+ @patch(f"{SOURCE_PATCH}.validate_surveysparrow_credentials")+ def test_delegates_with_resolved_base_url(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (True, None)++ ok, error = SurveySparrowSource().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://eu-api.surveysparrow.com")+++class TestSurveySparrowResumableManager:+ def test_returns_manager_bound_to_resume_config(self) -> None:+ manager = SurveySparrowSource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SurveySparrowResumeConfig+++class TestSurveySparrowSourceForPipeline:+ 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}.surveysparrow_source") as mock_source:+ mock_source.return_value = sentinel+ result = SurveySparrowSource().source_for_pipeline(+ _config(data_center="ca"), MagicMock(), self._inputs("responses")+ )++ assert result is sentinel+ kwargs = mock_source.call_args.kwargs+ assert kwargs["access_token"] == "token"+ assert kwargs["base_url"] == "https://ca-api.surveysparrow.com"+ assert kwargs["endpoint"] == "responses"++ def test_unknown_schema_raises(self) -> None:+ try:+ SurveySparrowSource().source_for_pipeline(_config(), MagicMock(), self._inputs("nope"))+ raise AssertionError("expected ValueError")+ except ValueError as e:+ assert "nope" in str(e)++ def test_responses_have_composite_key_and_datetime_partitioning(self) -> None:+ response = SurveySparrowSource().source_for_pipeline(_config(), MagicMock(), self._inputs("responses"))+ assert response.name == "responses"+ assert response.primary_keys == ["survey_id", "id"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["completed_time"]+ assert response.sort_mode == "asc"++ def test_questions_are_unpartitioned_with_composite_key(self) -> None:+ response = SurveySparrowSource().source_for_pipeline(_config(), MagicMock(), self._inputs("questions"))+ assert response.primary_keys == ["survey_id", "id"]+ assert response.partition_mode is None+ assert response.partition_keys is None+++class TestSurveySparrowNonRetryableErrors:+ def test_marks_auth_errors_non_retryable(self) -> None:+ errors = SurveySparrowSource().get_non_retryable_errors()+ assert any("401" in key for key in errors)+ assert any("403" in key for key in errors)