: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 simplesat import source (#68592)
Tom Owersae9acfe5fc51
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 60e643541084..b1020914d55f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -291,6 +291,7 @@ the row lists both.| shipstation | HTTP | requests | ✅ || shopify | HTTP | requests | ✅ || shortcut | HTTP | requests | ✅ |+| simplesat | HTTP | requests | ✅ || slack | HTTP | requests + `rest_source.RESTClient` | ✅ || smartsheet | HTTP | requests | ✅ || snapchat_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -655,7 +656,6 @@ doesn't conflict with concurrent PRs.- signnow- simfin- simplecast-- simplesat- smaily- smartengage- smartreachdiff --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 0231cc378b6f..dd26bf6fbd33 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@@ -3025,7 +3025,7 @@ class SimpleCastSourceConfig(config.Config):@config.configclass SimplesatSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/canonical_descriptions.pynew file mode 100644index 000000000000..de9e965860ac--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/canonical_descriptions.py@@ -0,0 +1,66 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the Simplesat API docs (https://documenter.getpostman.com/view/457268/UVRDGRZ2).+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "surveys": {+ "description": "A customer satisfaction survey (CSAT, CES, or NPS) configured in Simplesat.",+ "docs_url": "https://documenter.getpostman.com/view/457268/UVRDGRZ2",+ "columns": {+ "id": "The unique ID of the survey.",+ "name": "The survey name.",+ "brand_name": "The brand name shown to respondents.",+ "metric": "The metric the survey measures (e.g. CSAT, CES, NPS).",+ "survey_type": "The type of survey.",+ "survey_token": "The public token identifying the survey.",+ },+ },+ "questions": {+ "description": "A question belonging to a Simplesat survey.",+ "docs_url": "https://documenter.getpostman.com/view/457268/UVRDGRZ2",+ "columns": {+ "id": "The unique ID of the question.",+ "text": "The question text shown to respondents.",+ "metric": "The metric the question measures.",+ "order": "The display order of the question within the survey.",+ "choices": "The list of answer choices offered.",+ "rating_scale": "Whether the question uses a rating scale.",+ "required": "Whether an answer to the question is required.",+ "rules": "Conditional logic rules attached to the question.",+ "survey": "The survey this question belongs to.",+ },+ },+ "answers": {+ "description": "An individual answer submitted to a survey question.",+ "docs_url": "https://documenter.getpostman.com/view/457268/UVRDGRZ2",+ "columns": {+ "id": "The unique ID of the answer.",+ "choice": "The choice value selected by the respondent.",+ "choice_label": "The human-readable label of the selected choice.",+ "follow_up_answer": "The free-text follow-up comment, if any.",+ "sentiment": "The sentiment classification of the answer.",+ "published_as_testimonial": "Whether the answer has been published as a testimonial.",+ "response_id": "The ID of the response this answer is part of.",+ "question": "The question this answer responds to.",+ "survey": "The survey this answer belongs to.",+ "created": "When the answer was created.",+ "modified": "When the answer was last modified.",+ },+ },+ "responses": {+ "description": "A complete survey submission from a customer, grouping the individual answers.",+ "docs_url": "https://documenter.getpostman.com/view/457268/UVRDGRZ2",+ "columns": {+ "id": "The unique ID of the response.",+ "answers": "The individual answers included in this response.",+ "customer": "The customer who submitted the response.",+ "survey": "The survey that was answered.",+ "ticket": "The support ticket associated with the response, if any.",+ "ip_address": "The IP address the response was submitted from.",+ "created": "When the response was created.",+ "modified": "When the response was last modified.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/settings.pynew file mode 100644index 000000000000..7711b6fcf32e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/settings.py@@ -0,0 +1,33 @@+from dataclasses import dataclass, field+++@dataclass+class SimplesatEndpointConfig:+ name: str+ path: str+ # Simplesat list responses wrap records under a key named after the resource+ # (e.g. {"surveys": [...], "next": ...}), so the extraction key is per-endpoint.+ list_key: str+ # A few list endpoints are exposed only as POST `/<resource>/search` collection endpoints.+ method: str = "GET"+ # Simplesat object IDs are unique per account, so `id` is a safe primary key everywhere.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# Simplesat v1 top-level list endpoints. All are full-refresh only: while `answers` and+# `responses` accept optional start_date/end_date filters, the API's ordering guarantees for+# those filters aren't documented well enough to advance an incremental cursor safely, so a+# client-side scan would cost the same as a full refresh (see the implementing-warehouse-sources+# skill).+SIMPLESAT_ENDPOINTS: dict[str, SimplesatEndpointConfig] = {+ "surveys": SimplesatEndpointConfig(name="surveys", path="/surveys", list_key="surveys", method="GET"),+ "questions": SimplesatEndpointConfig(name="questions", path="/questions", list_key="questions", method="GET"),+ "answers": SimplesatEndpointConfig(name="answers", path="/answers/search", list_key="answers", method="POST"),+ "responses": SimplesatEndpointConfig(+ name="responses", path="/responses/search", list_key="responses", method="POST"+ ),+}++ENDPOINTS = tuple(SIMPLESAT_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/simplesat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/simplesat.pynew file mode 100644index 000000000000..f9b6d5f27d2f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/simplesat.py@@ -0,0 +1,189 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlsplit++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.settings import SIMPLESAT_ENDPOINTS++SIMPLESAT_BASE_URL = "https://api.simplesat.io/api/v1"+SIMPLESAT_HOST = "api.simplesat.io"+SIMPLESAT_PATH_PREFIX = "/api/v1"+# The list endpoints return up to 100 records per page; the largest page minimises round trips.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API key is genuine. The key is account-wide, so one probe+# validates access to every list endpoint.+DEFAULT_PROBE_PATH = "/surveys"+++class SimplesatRetryableError(Exception):+ pass+++class SimplesatResumeConfig:+ # Absolute URL of the next page to fetch, taken verbatim from the response body's `next`+ # field. Cursor pagination is deterministic, so a crashed full-refresh sync resumes from the+ # page after the last one yielded; merge dedupes on `id`.+ next_url: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"X-Simplesat-Token": api_key, "Accept": "application/json"}+++def _assert_same_origin(url: str) -> None:+ # The pagination cursor (`next`) comes from the response body and is followed with the same+ # session that carries `X-Simplesat-Token`. Pin it to the Simplesat API origin so a malformed+ # or malicious response can't redirect the customer's key to another host.+ parts = urlsplit(url)+ if parts.scheme != "https" or parts.hostname != SIMPLESAT_HOST or not parts.path.startswith(SIMPLESAT_PATH_PREFIX):+ raise SimplesatRetryableError(+ f"Simplesat returned an off-origin pagination URL: {parts.scheme}://{parts.netloc}"+ )+++@retry(+ retry=retry_if_exception_type((SimplesatRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ method: str,+ url: str,+ list_key: str,+ params: Optional[dict[str, Any]],+ json_body: Optional[dict[str, Any]],+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], Optional[str]]:+ if method == "POST":+ response = session.post(url, params=params, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS)+ else:+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise SimplesatRetryableError(f"Simplesat API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Simplesat API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Simplesat wraps the page in an object: {"<resource>": [...], "count": N, "next": ..., "previous": ...}.+ if not isinstance(data, dict):+ raise SimplesatRetryableError(f"Simplesat returned an unexpected payload for {url}: {type(data).__name__}")++ items = data.get(list_key)+ if not isinstance(items, list):+ raise SimplesatRetryableError(f"Simplesat returned a non-list `{list_key}` for {url}")++ next_url = data.get("next")+ if next_url is not None and not isinstance(next_url, str):+ raise SimplesatRetryableError(f"Simplesat returned a non-string `next` for {url}")++ return items, next_url+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SimplesatResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = SIMPLESAT_ENDPOINTS[endpoint]+ # Never follow redirects: the pagination cursor is user-supplied response data, so a 3xx could+ # otherwise smuggle the customer's API key to another host.+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,), allow_redirects=False)++ # The search-style collection endpoints are POST; an empty body means "no date filter",+ # i.e. every record — the full refresh we want.+ json_body: Optional[dict[str, Any]] = {} if config.method == "POST" else None++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume and resume.next_url:+ # Follow the saved cursor URL verbatim; it already carries the pagination params.+ _assert_same_origin(resume.next_url)+ url = resume.next_url+ params: Optional[dict[str, Any]] = None+ logger.debug(f"Simplesat: resuming {endpoint} from {url}")+ else:+ url = f"{SIMPLESAT_BASE_URL}{config.path}"+ params = {"page_size": PAGE_SIZE}++ while True:+ items, next_url = _fetch_page(session, config.method, url, config.list_key, params, json_body, logger)+ if items:+ yield items++ # A null `next` means we've reached the end of the collection.+ if not next_url:+ break++ # Follow the full `next` URL — it already carries page and page_size, so we don't re-send params.+ _assert_same_origin(next_url)+ url = next_url+ params = None+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(SimplesatResumeConfig(next_url=next_url))+++def simplesat_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SimplesatResumeConfig],+) -> SourceResponse:+ config = SIMPLESAT_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API key.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{SIMPLESAT_BASE_URL}{path}", params={"page_size": 1}, timeout=15)+ except Exception as e:+ return 0, f"Could not connect to Simplesat: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"Simplesat returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid Simplesat API key"+ return False, message or "Could not validate Simplesat API key"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/source.pyindex 6101f702a40f..6bb5dcd42f76 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SimplesatSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.settings import (+ ENDPOINTS,+ SIMPLESAT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.simplesat import (+ SimplesatResumeConfig,+ simplesat_source,+ validate_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SimplesatSource(SimpleSource[SimplesatSourceConfig]):+class SimplesatSource(ResumableSource[SimplesatSourceConfig, SimplesatResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SIMPLESAT@@ -24,7 +47,87 @@ class SimplesatSource(SimpleSource[SimplesatSourceConfig]):name=SchemaExternalDataSourceType.SIMPLESAT,category=DataWarehouseSourceCategory.CUSTOMER_SUPPORT,label="Simplesat",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Simplesat API key to pull your customer satisfaction survey data into the PostHog Data warehouse.++You can create an API key under **Settings → API keys** in [Simplesat](https://app.simplesat.io/). The key must include read scopes for each resource you want to sync — surveys, questions, answers, and responses.+""",iconPath="/static/services/simplesat.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/simplesat",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.simplesat.io": "Your Simplesat API key is invalid or has been revoked. Generate a new key under Settings → API keys, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.simplesat.io": "Your Simplesat API key does not have access to this data. Check the key's scopes, then reconnect.",+ }++ def get_schemas(+ self,+ config: SimplesatSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — Simplesat's list endpoints expose no reliably+ # ordered server-side timestamp filter, so there is no incremental cursor to advance.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: SimplesatSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # The API key is account-wide, so a single probe validates access to every schema.+ # Delegate to the transport-level helper so the status → message mapping lives in one place.+ return validate_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SimplesatResumeConfig]:+ return ResumableSourceManager[SimplesatResumeConfig](inputs, SimplesatResumeConfig)++ def source_for_pipeline(+ self,+ config: SimplesatSourceConfig,+ resumable_source_manager: ResumableSourceManager[SimplesatResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in SIMPLESAT_ENDPOINTS:+ raise ValueError(f"Unknown Simplesat schema '{inputs.schema_name}'")++ return simplesat_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/tests/test_simplesat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/tests/test_simplesat.pynew file mode 100644index 000000000000..e327fc48e783--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/tests/test_simplesat.py@@ -0,0 +1,275 @@+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat import simplesat+from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.settings import (+ ENDPOINTS,+ SIMPLESAT_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.simplesat import (+ SIMPLESAT_BASE_URL,+ SimplesatResumeConfig,+ SimplesatRetryableError,+ check_access,+ get_rows,+ simplesat_source,+ validate_credentials,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = simplesat._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: SimplesatResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SimplesatResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SimplesatResumeConfig | None:+ return self._state++ def save_state(self, data: SimplesatResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: dict[Optional[str], tuple[list[dict], Optional[str]]],+ endpoint: str = "surveys",+ ) -> list[dict]:+ # Keyed by `next_url` (None for the first request), value is (items, next_url) for that page.+ seen_urls: list[str] = []++ def fake_fetch(+ session: Any,+ method: str,+ url: str,+ list_key: str,+ params: Any,+ json_body: Any,+ logger: Any,+ ) -> tuple[list[dict], Optional[str]]:+ seen_urls.append(url)+ # On the first request `params` is set; on cursor follow-ups it is None.+ key = url if url in pages else None+ return pages[key]++ monkeypatch.setattr(simplesat, "_fetch_page", fake_fetch)+ monkeypatch.setattr(simplesat, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_key="ss-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows++ def test_single_page_with_null_next_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([{"id": 1}, {"id": 2}], None)})+ assert rows == [{"id": 1}, {"id": 2}]+ # `next` is null, so we stop without persisting resume state.+ assert manager.saved == []++ def test_follows_next_url_until_null(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ next_url = f"{SIMPLESAT_BASE_URL}/surveys?page=2&page_size=100"+ pages: dict[Optional[str], tuple[list[dict], Optional[str]]] = {+ None: ([{"id": 1}], next_url),+ next_url: ([{"id": 2}], None),+ }+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 1}, {"id": 2}]+ # State is saved with the cursor after the first page, then we stop on the null `next`.+ assert [s.next_url for s in manager.saved] == [next_url]++ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:+ next_url = f"{SIMPLESAT_BASE_URL}/surveys?page=2&page_size=100"+ manager = _FakeResumableManager(SimplesatResumeConfig(next_url=next_url))+ # The first page URL must never be fetched on resume.+ pages: dict[Optional[str], tuple[list[dict], Optional[str]]] = {next_url: ([{"id": 5}], None)}+ rows = self._collect(manager, monkeypatch, pages)+ assert rows == [{"id": 5}]++ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = self._collect(manager, monkeypatch, {None: ([], None)})+ assert rows == []+ assert manager.saved == []++ def test_off_origin_next_url_raises(self, monkeypatch: Any) -> None:+ # A pagination cursor pointing off the Simplesat API origin must not be followed — it would+ # leak the customer's API key to another host.+ manager = _FakeResumableManager()+ evil = "https://evil.example.com/api/v1/surveys?page=2"+ with pytest.raises(SimplesatRetryableError):+ self._collect(manager, monkeypatch, {None: ([{"id": 1}], evil)})++ def test_off_origin_resume_url_raises(self, monkeypatch: Any) -> None:+ # A tampered saved cursor is rejected before any request is made.+ evil = "https://evil.example.com/api/v1/surveys?page=2"+ manager = _FakeResumableManager(SimplesatResumeConfig(next_url=evil))+ with pytest.raises(SimplesatRetryableError):+ self._collect(manager, monkeypatch, {evil: ([{"id": 5}], None)})+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"surveys": []}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ session.post.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(SimplesatRetryableError):+ _fetch_page_unwrapped(session, "GET", f"{SIMPLESAT_BASE_URL}/surveys", "surveys", {}, None, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "GET", f"{SIMPLESAT_BASE_URL}/surveys", "surveys", {}, None, MagicMock())++ def test_success_extracts_list_and_next(self) -> None:+ body = {"surveys": [{"id": 1}], "count": 1, "next": None, "previous": None}+ session = self._session_returning(200, body)+ items, next_url = _fetch_page_unwrapped(+ session, "GET", f"{SIMPLESAT_BASE_URL}/surveys", "surveys", {}, None, MagicMock()+ )+ assert items == [{"id": 1}]+ assert next_url is None++ def test_success_returns_next_url(self) -> None:+ next_url = f"{SIMPLESAT_BASE_URL}/surveys?page=2"+ body = {"surveys": [{"id": 1}], "next": next_url}+ session = self._session_returning(200, body)+ _items, returned = _fetch_page_unwrapped(+ session, "GET", f"{SIMPLESAT_BASE_URL}/surveys", "surveys", {}, None, MagicMock()+ )+ assert returned == next_url++ def test_non_dict_body_is_retryable(self) -> None:+ session = self._session_returning(200, [{"id": 1}])+ with pytest.raises(SimplesatRetryableError):+ _fetch_page_unwrapped(session, "GET", f"{SIMPLESAT_BASE_URL}/surveys", "surveys", {}, None, MagicMock())++ def test_non_list_resource_key_is_retryable(self) -> None:+ session = self._session_returning(200, {"surveys": {"nope": 1}})+ with pytest.raises(SimplesatRetryableError):+ _fetch_page_unwrapped(session, "GET", f"{SIMPLESAT_BASE_URL}/surveys", "surveys", {}, None, MagicMock())++ def test_missing_resource_key_is_retryable(self) -> None:+ # A response envelope without the resource key must fail loudly rather than sync zero rows.+ session = self._session_returning(200, {"count": 0, "next": None})+ with pytest.raises(SimplesatRetryableError):+ _fetch_page_unwrapped(session, "GET", f"{SIMPLESAT_BASE_URL}/surveys", "surveys", {}, None, MagicMock())++ def test_post_endpoint_uses_post_with_json_body(self) -> None:+ body = {"answers": [{"id": 1}], "next": None}+ session = self._session_returning(200, body)+ url = f"{SIMPLESAT_BASE_URL}/answers/search"+ items, _next = _fetch_page_unwrapped(session, "POST", url, "answers", {"page_size": 100}, {}, MagicMock())+ assert items == [{"id": 1}]+ session.post.assert_called_once()+ _, kwargs = session.post.call_args+ assert kwargs["json"] == {}+ session.get.assert_not_called()+++class TestCheckAccess:+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ monkeypatch.setattr(simplesat, "make_tracked_session", lambda **kwargs: session)+ return session++ @pytest.mark.parametrize(+ "status, ok, expected_status, expected_message",+ [+ (200, True, 200, None),+ (401, False, 401, None),+ (403, False, 403, None),+ (500, False, 500, "Simplesat returned HTTP 500"),+ ],+ )+ def test_status_mapping(+ self, status: int, ok: bool, expected_status: int, expected_message: str | None, monkeypatch: Any+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ self._patch_session(monkeypatch, response)+ assert check_access("ss-key") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))+ status, message = check_access("ss-key")+ assert status == 0+ assert message is not None and "boom" in message++ @pytest.mark.parametrize(+ "status, expected_valid, expected_message",+ [+ (200, True, None),+ (401, False, "Invalid Simplesat API key"),+ (403, False, "Invalid Simplesat API key"),+ (500, False, "Simplesat returned HTTP 500"),+ ],+ )+ def test_validate_credentials(+ self, status: int, expected_valid: bool, expected_message: str | None, monkeypatch: Any+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ self._patch_session(monkeypatch, response)+ assert validate_credentials("ss-key") == (expected_valid, expected_message)+++class TestSimplesatSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = simplesat_source(+ api_key="ss-key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ # No stable creation timestamp is guaranteed across every object, so we don't partition.+ assert response.partition_mode is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in SIMPLESAT_ENDPOINTS.values())+ assert set(SIMPLESAT_ENDPOINTS) == set(ENDPOINTS)++ def test_list_key_matches_endpoint_name(self) -> None:+ assert all(config.list_key == config.name for config in SIMPLESAT_ENDPOINTS.values())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/tests/test_simplesat_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/tests/test_simplesat_source.pynew file mode 100644index 000000000000..ad2bc0010e6a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/simplesat/tests/test_simplesat_source.py@@ -0,0 +1,126 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++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 SimplesatSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.simplesat import SimplesatResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.source import SimplesatSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestSimplesatSource:+ def setup_method(self) -> None:+ self.source = SimplesatSource()+ self.team_id = 123+ self.config = SimplesatSourceConfig(api_key="ss-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SIMPLESAT++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Simplesat"+ assert config.label == "Simplesat"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible — it must not carry the scaffolding flag.+ assert not config.unreleasedSource+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/simplesat"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved key against another account.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["answers"])+ assert len(schemas) == 1+ assert schemas[0].name == "answers"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.simplesat.io/api/v1/surveys?page_size=100",+ "403 Client Error: Forbidden for url: https://api.simplesat.io/api/v1/questions?page_size=100",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @pytest.mark.parametrize(+ "unrelated_error",+ [+ "500 Server Error: Internal Server Error for url: https://api.simplesat.io/api/v1/surveys",+ "429 Client Error: Too Many Requests for url: https://api.simplesat.io/api/v1/questions",+ ],+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.source.validate_credentials"+ )+ def test_validate_credentials_delegates_to_transport(self, mock_validate: mock.MagicMock) -> None:+ # The status → message mapping is covered in test_simplesat.py; here we only lock in that the+ # source passes the api key through and returns the transport helper's verdict unchanged.+ mock_validate.return_value = (False, "Invalid Simplesat API key")+ result = self.source.validate_credentials(self.config, self.team_id)+ mock_validate.assert_called_once_with(self.config.api_key)+ assert result == (False, "Invalid Simplesat API key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SimplesatResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.simplesat.source.simplesat_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "surveys"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "ss-key"+ assert kwargs["endpoint"] == "surveys"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown Simplesat schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)