: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 qualtrics source (#73793)
Tom Owers1433fe254ca0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 2b6f15da9d9a..89400ec69bea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -480,6 +480,7 @@ the row lists both.| pylon | HTTP | requests | ✅ || pypi | HTTP | requests | ✅ || qualaroo | HTTP | requests | ✅ |+| qualtrics | HTTP | requests | ✅ || qualys_vmdr | HTTP (XML responses) | requests | ✅ || railway | HTTP (GraphQL) | requests | ✅ || recurly | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1211,7 +1212,6 @@ doesn't conflict with concurrent PRs.- pubnub- qdrant- qonto-- qualtrics- quay- quickbooks- railzdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qualtrics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qualtrics.pyindex b64b80b6eacb..3e4f08983940 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qualtrics.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/qualtrics.py@@ -1,9 +1,20 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class QualtricsAuthMethodConfig(config.Config):+ selection: Literal["api_token", "oauth_client_credentials"] = "api_token"+ api_token: str | None = None+ client_id: str | None = None+ client_secret: str | None = None++@config.configclass QualtricsSourceConfig(config.Config):- pass+ datacenter_id: str+ auth_method: QualtricsAuthMethodConfigdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/canonical_descriptions.pynew file mode 100644index 000000000000..5490670ce0bd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/canonical_descriptions.py@@ -0,0 +1,109 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "surveys": {+ "description": "Every survey in the Qualtrics brand the credentials can see, with its owner and status.",+ "docs_url": "https://api.qualtrics.com/",+ "columns": {+ "id": "Unique survey identifier, prefixed with `SV_`.",+ "name": "Name of the survey as shown in the Qualtrics project list.",+ "ownerId": "Identifier of the Qualtrics user who owns the survey.",+ "lastModified": "Timestamp of the most recent change to the survey.",+ "creationDate": "Timestamp the survey was created.",+ "isActive": "Whether the survey is currently collecting responses.",+ },+ },+ "survey_responses": {+ "description": "Recorded responses for every survey, pulled through the Qualtrics response export.",+ "docs_url": "https://api.qualtrics.com/",+ "columns": {+ "responseId": "Unique response identifier, prefixed with `R_`.",+ "surveyId": "Identifier of the survey the response belongs to.",+ "recordedDate": "Timestamp the response was recorded, and the cursor used for incremental syncs.",+ "startDate": "Timestamp the respondent started the survey.",+ "endDate": "Timestamp the respondent last interacted with the survey.",+ "status": "Response type code, for example survey preview, test response, or a real response.",+ "progress": "How far through the survey the respondent got, as a percentage.",+ "duration": "Seconds the respondent spent on the survey.",+ "finished": "Whether the respondent reached the end of the survey.",+ "distributionChannel": "How the response was collected, for example anonymous link or email.",+ "userLanguage": "Language the survey was taken in.",+ "values": "JSON object of raw answer values keyed by question id, plus embedded data.",+ "labels": "JSON object of the human-readable choice labels matching `values`.",+ "displayedFields": "JSON array of the question ids that were displayed to the respondent.",+ "displayedValues": "JSON object of the choices that were displayed for each question.",+ },+ },+ "survey_questions": {+ "description": "Question definitions for each survey, from the survey definition API.",+ "docs_url": "https://api.qualtrics.com/",+ "columns": {+ "QuestionID": "Identifier of the question within its survey, for example `QID3`.",+ "surveyId": "Identifier of the survey the question belongs to.",+ "QuestionText": "Question text as shown to respondents.",+ "QuestionType": "Question type code, for example `MC` for multiple choice or `TE` for text entry.",+ "Selector": "Sub-type that refines the question type, for example single answer or multiple answer.",+ "DataExportTag": "Short tag used as the question's column name in Qualtrics exports.",+ "QuestionDescription": "Internal description of the question.",+ "Choices": "Answer choices defined for the question.",+ },+ },+ "distributions": {+ "description": "Distributions (email, SMS and link invitations) sent for each survey.",+ "docs_url": "https://api.qualtrics.com/",+ "columns": {+ "id": "Unique distribution identifier, prefixed with `EMD_`.",+ "surveyId": "Identifier of the survey the distribution was sent for.",+ "parentDistributionId": "Identifier of the distribution this one follows up on, if any.",+ "ownerId": "Identifier of the Qualtrics user who created the distribution.",+ "organizationId": "Identifier of the Qualtrics organization the distribution belongs to.",+ "requestStatus": "Current state of the distribution request, for example pending or done.",+ "requestType": "Kind of distribution, for example an invite or a reminder.",+ "sendDate": "Timestamp the distribution was scheduled to send.",+ "createdDate": "Timestamp the distribution was created.",+ "modifiedDate": "Timestamp the distribution was last changed.",+ "stats": "Delivery counters for the distribution, such as sent, opened and finished.",+ },+ },+ "users": {+ "description": "Users in the Qualtrics brand, with their division, role and account status.",+ "docs_url": "https://api.qualtrics.com/",+ "columns": {+ "id": "Unique user identifier, prefixed with `UR_`.",+ "username": "Login name of the user.",+ "email": "Email address of the user.",+ "firstName": "First name of the user.",+ "lastName": "Last name of the user.",+ "userType": "Permission set assigned to the user.",+ "divisionId": "Identifier of the division the user belongs to.",+ "organizationId": "Identifier of the Qualtrics organization the user belongs to.",+ "accountStatus": "Whether the account is active or disabled.",+ "unsubscribed": "Whether the user has unsubscribed from Qualtrics emails.",+ "language": "Interface language set for the user.",+ },+ },+ "groups": {+ "description": "Groups used to share surveys, libraries and other assets between Qualtrics users.",+ "docs_url": "https://api.qualtrics.com/",+ "columns": {+ "id": "Unique group identifier, prefixed with `GR_`.",+ "name": "Name of the group.",+ "type": "Group type, which controls the permissions members inherit.",+ "divisionId": "Identifier of the division the group belongs to, if any.",+ "organizationId": "Identifier of the Qualtrics organization the group belongs to.",+ },+ },+ "divisions": {+ "description": "Divisions used to partition users and content inside a Qualtrics brand.",+ "docs_url": "https://api.qualtrics.com/",+ "columns": {+ "divisionId": "Unique division identifier, prefixed with `DV_`.",+ "name": "Name of the division.",+ "divisionStatus": "Whether the division is active or disabled.",+ "creationDate": "Timestamp the division was created.",+ "creatorId": "Identifier of the Qualtrics user who created the division.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.pynew file mode 100644index 000000000000..adbe4396d5dc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py@@ -0,0 +1,854 @@+import re+import json+import time+import base64+import zipfile+import tempfile+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import IO, Any, Literal, Optional+from urllib.parse import urlencode, urlparse++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.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.qualtrics.settings import (+ QUALTRICS_DEFAULT_DOMAIN_SUFFIX,+ QUALTRICS_ENDPOINTS,+ VALIDATION_PATHS,+ QualtricsEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5++# The brand host is customer-supplied, so no response body is ever buffered unbounded. JSON+# collection pages are small (Qualtrics caps them at 100 elements), so this leaves ample room.+MAX_RESPONSE_BYTES = 32 * 1024 * 1024+_RESPONSE_CHUNK_BYTES = 64 * 1024+_ERROR_BODY_PREVIEW_BYTES = 2 * 1024+# Wall-clock budget for one body. `requests`' timeout only bounds each socket read, so a host+# dribbling bytes under that timeout could otherwise hold a worker open indefinitely.+MAX_DOWNLOAD_SECONDS = 900++# Response exports are the one large payload: the archive is spooled to disk past this size+# and refused past the hard cap, and the decompressed stream is capped separately so a+# zip bomb can't amplify a small download into unbounded memory.+EXPORT_SPOOL_MAX_BYTES = 32 * 1024 * 1024+MAX_EXPORT_ARCHIVE_BYTES = 2 * 1024 * 1024 * 1024+MAX_EXPORT_DECOMPRESSED_BYTES = 16 * 1024 * 1024 * 1024+# Cap a single NDJSON line so a newline-free member can't buffer unbounded before the byte+# budget is checked. A real Qualtrics response row is far smaller than this.+MAX_EXPORT_LINE_BYTES = 16 * 1024 * 1024+# Flush a batch once its accumulated rows reach this many serialized bytes, so a run of large+# rows can't pin far more than this in memory before the row-count batch size is hit.+MAX_EXPORT_BATCH_BYTES = 32 * 1024 * 1024+# A real export is a single NDJSON member; `zipfile` builds a `ZipInfo` per entry as soon as it+# reads the central directory, so cap the declared member count before that memory is spent.+MAX_EXPORT_ARCHIVE_MEMBERS = 1024++# Export jobs are asynchronous: create, then poll until Qualtrics reports `complete`.+EXPORT_POLL_INTERVAL_SECONDS = 3.0+MAX_EXPORT_POLL_SECONDS = 60 * 60++# Rows are yielded to the pipeline in batches of this many.+EXPORT_BATCH_SIZE = 1000++# A server that keeps returning a `nextPage` forever would pin the (up to week-long) activity+# in an endless fetch loop. At 100 elements per page this is far beyond any real brand.+MAX_PAGES = 50_000++# The fan-out survey-id list is held whole in memory, so bound both the per-id length (real+# Qualtrics ids are ~18 chars) and the total count (far beyond any real brand) so a custom host+# streaming endless over-long ids can't exhaust the worker.+MAX_SURVEY_ID_LENGTH = 64+MAX_SURVEY_COUNT = 200_000++# OAuth2 client-credentials tokens last ~1h; re-mint before the deadline so no request rides+# a token that expires mid-flight.+TOKEN_REFRESH_MARGIN_SECONDS = 60+DEFAULT_TOKEN_LIFETIME_SECONDS = 60 * 60++HOST_NOT_ALLOWED_ERROR = "Qualtrics host is not allowed"+INCOMPLETE_CREDENTIALS_ERROR = "Qualtrics credentials are incomplete"+EXPORT_FAILED_ERROR = "Qualtrics response export failed"++_HOST_PATTERN = re.compile(r"^[A-Za-z0-9.\-]+$")+_SURVEY_ID_PATTERN = re.compile(r"^[A-Za-z0-9_\-]+$")+++class QualtricsRetryableError(Exception):+ pass+++class QualtricsHostNotAllowedError(Exception):+ pass+++class QualtricsConfigurationError(Exception):+ pass+++class QualtricsResponseTooLargeError(Exception):+ pass+++class QualtricsResponseTooSlowError(Exception):+ pass+++class QualtricsPaginationLimitError(Exception):+ pass+++class QualtricsExportFailedError(Exception):+ pass+++class QualtricsResumeConfig:+ # Full URL of the next collection page to fetch (top-level list endpoints).+ next_page: str | None = None+ # Number of parent surveys already walked to completion (fan-out endpoints). Restarting+ # the in-flight survey is intentional — merge dedupes its rows on the primary key.+ parent_index: int = 0+++class QualtricsCredentials:+ method: Literal["api_token", "oauth_client_credentials"]+ api_token: str | None = None+ client_id: str | None = None+ client_secret: str | None = None++ def secret_values(self) -> tuple[str, ...]:+ return tuple(value for value in (self.api_token, self.client_secret) if value)+++def normalize_host(datacenter_id: str) -> str:+ """Turn whatever the user typed into a bare Qualtrics host.++ Accepts a datacenter id (``iad1``), a full host (``iad1.qualtrics.com``), or a pasted URL+ (``https://iad1.qualtrics.com/API/v3/``). A bare id gains the default Qualtrics domain;+ anything already carrying a dot is treated as a host so brands on a custom domain work.+ """+ host = datacenter_id.strip()+ host = re.sub(r"^https?://", "", host, flags=re.IGNORECASE)+ host = host.split("/")[0].strip().rstrip("/").lower()+ if host and "." not in host:+ host = f"{host}{QUALTRICS_DEFAULT_DOMAIN_SUFFIX}"+ return host+++def validate_host(datacenter_id: str) -> str:+ host = normalize_host(datacenter_id)+ if not host or not _HOST_PATTERN.match(host):+ raise QualtricsConfigurationError("Invalid Qualtrics datacenter ID")+ return host+++def base_url(host: str, api_version: str) -> str:+ return f"https://{host}/API/{api_version}"+++def _format_datetime_z(value: datetime) -> str:+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")+++def format_incremental_value(value: Any) -> str:+ """Qualtrics export filters take ISO 8601 instants (``2026-01-01T00:00:00Z``)."""+ if isinstance(value, datetime):+ return _format_datetime_z(value)+ if isinstance(value, date):+ return _format_datetime_z(datetime.combine(value, datetime.min.time(), tzinfo=UTC))+ return str(value)+++def _read_capped(response: requests.Response, max_bytes: int) -> bytes:+ """Read a streamed body, refusing one past ``max_bytes`` or ``MAX_DOWNLOAD_SECONDS``.++ ``iter_content`` decodes any content-encoding, so the cap bounds the decompressed body and a+ compressed one cannot slip past it. Both caps are permanent failures — re-fetching the same+ URL returns the same oversized or slow body.+ """+ chunks: list[bytes] = []+ total = 0+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ try:+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ raise QualtricsResponseTooSlowError(+ f"Qualtrics response exceeded the {MAX_DOWNLOAD_SECONDS}s download budget; aborting"+ )+ if not chunk:+ continue+ total += len(chunk)+ if total > max_bytes:+ raise QualtricsResponseTooLargeError(+ f"Qualtrics response exceeded the {max_bytes}-byte limit; refusing to buffer it"+ )+ chunks.append(chunk)+ finally:+ response.close()+ return b"".join(chunks)+++def _read_capped_json(response: requests.Response) -> Any:+ return json.loads(_read_capped(response, MAX_RESPONSE_BYTES))+++def _read_body_preview(response: requests.Response) -> str:+ chunks: list[bytes] = []+ total = 0+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ break+ if not chunk:+ continue+ chunks.append(chunk)+ total += len(chunk)+ if total >= _ERROR_BODY_PREVIEW_BYTES:+ break+ return b"".join(chunks)[:_ERROR_BODY_PREVIEW_BYTES].decode("utf-8", errors="replace")+++def _guard_response(response: requests.Response, url: str, logger: FilteringBoundLogger | None = None) -> None:+ """Classify a response before its body is read: retryable, redirect, or hard error."""+ if response.status_code == 429 or response.status_code >= 500:+ raise QualtricsRetryableError(f"Qualtrics API error (retryable): status={response.status_code}, url={url}")++ # A 3xx is not an error status, so reject it explicitly rather than following it to a+ # potentially internal Location (SSRF).+ if response.is_redirect or response.is_permanent_redirect:+ raise QualtricsHostNotAllowedError(+ f"Qualtrics API returned an unexpected redirect (status={response.status_code}); refusing to follow it"+ )++ if not response.ok:+ if logger is not None:+ logger.error(+ f"Qualtrics API error: status={response.status_code}, body={_read_body_preview(response)}, url={url}"+ )+ response.raise_for_status()+++_retry_write = retry(+ retry=retry_if_exception_type((QualtricsRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+++class QualtricsAuthManager:+ """Builds the auth header for both Qualtrics auth paths.++ An API token rides the ``X-API-TOKEN`` header verbatim. OAuth2 client credentials are+ exchanged at ``POST /oauth2/token`` for a ~1h bearer token, cached and re-minted before it+ expires so a long sync never rides a dead token.+ """++ def __init__(self, session: requests.Session, host: str, credentials: QualtricsCredentials) -> None:+ self._session = session+ self._host = host+ self._credentials = credentials+ self._token: str | None = None+ self._deadline: float = 0.0++ def headers(self) -> dict[str, str]:+ if self._credentials.method == "api_token":+ if not self._credentials.api_token:+ raise QualtricsConfigurationError(f"{INCOMPLETE_CREDENTIALS_ERROR}: API token required")+ return {"X-API-TOKEN": self._credentials.api_token, "Accept": "application/json"}+ return {"Authorization": f"Bearer {self._get_token()}", "Accept": "application/json"}++ def _get_token(self) -> str:+ if self._token is None or time.monotonic() >= self._deadline - TOKEN_REFRESH_MARGIN_SECONDS:+ self._mint()+ assert self._token is not None+ return self._token++ @_retry_write+ def _mint(self) -> None:+ if not self._credentials.client_id or not self._credentials.client_secret:+ raise QualtricsConfigurationError(f"{INCOMPLETE_CREDENTIALS_ERROR}: client ID and client secret required")++ basic = base64.b64encode(f"{self._credentials.client_id}:{self._credentials.client_secret}".encode()).decode()+ url = f"https://{self._host}/oauth2/token"+ # The transport's Retry policy only covers idempotent methods, so token mints (POST)+ # carry their own bounded retry via `_retry_write` rather than a second status layer.+ response = self._session.post(+ url,+ data={"grant_type": "client_credentials"},+ headers={"Authorization": f"Basic {basic}", "Content-Type": "application/x-www-form-urlencoded"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ )+ try:+ _guard_response(response, url)+ payload = _read_capped_json(response)+ finally:+ response.close()++ if not isinstance(payload, dict):+ raise QualtricsConfigurationError(f"{INCOMPLETE_CREDENTIALS_ERROR}: unexpected OAuth token response")+ token = payload.get("access_token")+ if not token:+ raise QualtricsConfigurationError(f"{INCOMPLETE_CREDENTIALS_ERROR}: OAuth token endpoint returned no token")+ self._token = token+ expires_in = payload.get("expires_in")+ self._deadline = time.monotonic() + (+ float(expires_in) if expires_in is not None else DEFAULT_TOKEN_LIFETIME_SECONDS+ )+++class QualtricsClient:+ """Thin request layer over the Qualtrics v3 API, sharing one auth manager per sync."""++ def __init__(+ self,+ host: str,+ credentials: QualtricsCredentials,+ api_version: str,+ logger: FilteringBoundLogger | None = None,+ ) -> None:+ self.host = host+ self.api_version = api_version+ self._logger = logger+ # Token responses carry the bearer credential in their body, which the name-based+ # sample scrubbers can't recognise — keep auth exchanges out of sample capture.+ self._auth = QualtricsAuthManager(+ make_tracked_session(capture=False, redact_values=credentials.secret_values()),+ host,+ credentials,+ )+ self._session = make_tracked_session(redact_values=credentials.secret_values())++ @property+ def base_url(self) -> str:+ return base_url(self.host, self.api_version)++ def url(self, path: str, params: dict[str, Any] | None = None) -> str:+ url = f"{self.base_url}{path}"+ return f"{url}?{urlencode(params, doseq=True)}" if params else url++ def _assert_same_host(self, url: str) -> None:+ """Follow-on URLs from the API body must stay on the configured brand host (SSRF)."""+ parsed = urlparse(url)+ if parsed.scheme != "https" or parsed.hostname != self.host:+ raise QualtricsHostNotAllowedError(f"{HOST_NOT_ALLOWED_ERROR}: {url}")++ def get(self, url: str) -> requests.Response:+ self._assert_same_host(url)+ return self._session.get(+ url,+ headers=self._auth.headers(),+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ )++ def get_json(self, url: str) -> Any:+ response = self.get(url)+ try:+ _guard_response(response, url, self._logger)+ return _read_capped_json(response)+ finally:+ response.close()++ @_retry_write+ def post_json(self, url: str, body: dict[str, Any]) -> Any:+ self._assert_same_host(url)+ response = self._session.post(+ url,+ json=body,+ headers={**self._auth.headers(), "Content-Type": "application/json"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ stream=True,+ )+ try:+ _guard_response(response, url, self._logger)+ return _read_capped_json(response)+ finally:+ response.close()+++def _result(payload: Any) -> dict[str, Any]:+ """Pull the `result` object out of a Qualtrics envelope, tolerating any non-dict shape.++ Every Qualtrics v3 response nests its payload under `result`, but a misbehaving or custom+ host could return valid JSON that isn't a dict — treat anything unexpected as empty rather+ than letting `.get()` raise mid-sync.+ """+ result = payload.get("result") if isinstance(payload, dict) else None+ return result if isinstance(result, dict) else {}+++def _elements(payload: Any) -> list[dict[str, Any]]:+ elements = _result(payload).get("elements")+ return elements if isinstance(elements, list) else []+++def _next_page(payload: Any) -> str | None:+ next_page = _result(payload).get("nextPage")+ return next_page if isinstance(next_page, str) and next_page else None+++def _iter_collection(+ client: QualtricsClient,+ first_url: str,+ resumable_source_manager: ResumableSourceManager[QualtricsResumeConfig] | None,+ start_url: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ """Walk a `result.elements` collection, following `result.nextPage` until it runs out."""+ url = start_url or first_url+ pages = 0++ while True:+ if pages >= MAX_PAGES:+ raise QualtricsPaginationLimitError(+ f"Qualtrics pagination exceeded {MAX_PAGES} pages without terminating: {first_url}"+ )++ payload = client.get_json(url)+ elements = _elements(payload)+ if elements:+ yield elements++ next_url = _next_page(payload)+ if not next_url:+ break++ # Saved AFTER yielding so a crash re-yields the last page rather than skipping it.+ if resumable_source_manager is not None:+ resumable_source_manager.save_state(QualtricsResumeConfig(next_page=next_url))+ url = next_url+ pages += 1+++def _survey_ids(client: QualtricsClient) -> list[str]:+ """Collect the survey ids the fan-out endpoints iterate.++ Ids go straight into request paths, so anything that isn't a plain Qualtrics id+ (`SV_...`) is dropped rather than allowed to steer the URL. The list is fully materialized —+ resuming the fan-out addresses surveys by index — so an id-length cap and a total-count cap+ keep a host that streams endless over-long ids from exhausting worker memory.+ """+ ids: list[str] = []+ for page in _iter_collection(client, client.url("/surveys"), resumable_source_manager=None):+ for element in page:+ raw = element.get("id")+ if not raw:+ continue+ survey_id = str(raw)+ if len(survey_id) > MAX_SURVEY_ID_LENGTH or not _SURVEY_ID_PATTERN.match(survey_id):+ continue+ ids.append(survey_id)+ if len(ids) > MAX_SURVEY_COUNT:+ raise QualtricsResponseTooLargeError(+ f"Qualtrics returned more than {MAX_SURVEY_COUNT} surveys; refusing to buffer them all"+ )+ return ids+++class _DecompressionBudget:+ """One decompressed-byte budget, shared across every member of an export archive.++ A single counter across the whole archive stops a multi-member zip from bypassing the cap:+ each member could stay under the limit while their aggregate decompressed size blows past it.+ """++ def __init__(self, limit: int) -> None:+ self._limit = limit+ self._total = 0++ def charge(self, n: int) -> None:+ self._total += n+ if self._total > self._limit:+ raise QualtricsResponseTooLargeError(f"Qualtrics export exceeded the {self._limit}-byte decompressed limit")+++def _parse_ndjson_line(line: bytes) -> Iterator[dict[str, Any]]:+ stripped = line.strip()+ if not stripped:+ return+ parsed = json.loads(stripped.decode("utf-8", errors="replace"))+ if isinstance(parsed, dict):+ yield parsed+++def _iter_ndjson(stream: IO[bytes], budget: _DecompressionBudget) -> Iterator[dict[str, Any]]:+ """Parse an NDJSON stream from bounded binary chunks, charging bytes to a shared budget.++ Reading raw chunks (rather than `TextIOWrapper` line iteration) keeps a single newline-free+ member from allocating an unbounded line before the byte budget is ever consulted.+ """+ buffer = bytearray()+ while True:+ chunk = stream.read(_RESPONSE_CHUNK_BYTES)+ if not chunk:+ break+ budget.charge(len(chunk))+ buffer.extend(chunk)+ newline = buffer.rfind(b"\n")+ if newline != -1:+ complete = bytes(buffer[: newline + 1])+ del buffer[: newline + 1]+ for line in complete.splitlines():+ yield from _parse_ndjson_line(line)+ if len(buffer) > MAX_EXPORT_LINE_BYTES:+ raise QualtricsResponseTooLargeError(+ f"Qualtrics export line exceeded the {MAX_EXPORT_LINE_BYTES}-byte limit"+ )+ if buffer:+ yield from _parse_ndjson_line(bytes(buffer))+++_EOCD_SIGNATURE = b"PK\x05\x06"+# The zip end-of-central-directory record is 22 bytes plus a comment of up to 65535 bytes.+_EOCD_MAX_SCAN_BYTES = 22 + 65535+# Fixed size of a central-directory file header; the real header is this plus name/extra/comment.+_CENTRAL_DIR_HEADER_MIN_BYTES = 46+++def _guard_zip_central_directory(buffer: IO[bytes]) -> None:+ """Reject an archive whose central directory is large enough to materialize too many members.++ `zipfile` reads the whole central directory and builds a `ZipInfo` per file header (each at+ least `_CENTRAL_DIR_HEADER_MIN_BYTES`), looping until it consumes the size-of-central-directory+ field of the trailing end-of-central-directory record — the same record it selects. Bounding+ that byte length before construction caps the entry count at `MAX_EXPORT_ARCHIVE_MEMBERS` no+ matter what the record's untrusted entry-count field claims, so a spoofed trailing EOCD+ declaring one member can't smuggle a huge directory past the guard. The ZIP64 sentinel+ (0xFFFFFFFF) reads well past the cap and is rejected here too — a real Qualtrics export stays+ well under 4 GiB with a single member.+ """+ max_central_directory_bytes = MAX_EXPORT_ARCHIVE_MEMBERS * _CENTRAL_DIR_HEADER_MIN_BYTES+ buffer.seek(0, 2)+ size = buffer.tell()+ scan = min(size, len(_EOCD_SIGNATURE) + _EOCD_MAX_SCAN_BYTES)+ buffer.seek(size - scan)+ tail = buffer.read(scan)+ marker = tail.rfind(_EOCD_SIGNATURE)+ # A missing/short record isn't our concern — `zipfile` raises its own BadZipFile for that.+ if marker == -1 or marker + 16 > len(tail):+ return+ central_directory_bytes = int.from_bytes(tail[marker + 12 : marker + 16], "little")+ if central_directory_bytes > max_central_directory_bytes:+ raise QualtricsResponseTooLargeError(+ f"Qualtrics export archive central directory is {central_directory_bytes} bytes, "+ f"exceeding the {max_central_directory_bytes}-byte limit"+ )+++def _iter_export_file(response: requests.Response) -> Iterator[dict[str, Any]]:+ """Stream the export download, transparently unpacking Qualtrics' zip envelope.++ `compress=true` is the API default and yields a zip holding one NDJSON member, but the flag+ is advisory — an uncompressed body is parsed directly. The archive is spooled (memory, then+ disk) because `zipfile` needs a seekable file, while the decompressed member is read as a+ stream so a large export never materializes whole.+ """+ with tempfile.SpooledTemporaryFile(max_size=EXPORT_SPOOL_MAX_BYTES) as buffer:+ total = 0+ deadline = time.monotonic() + MAX_DOWNLOAD_SECONDS+ try:+ for chunk in response.iter_content(chunk_size=_RESPONSE_CHUNK_BYTES):+ if time.monotonic() > deadline:+ raise QualtricsResponseTooSlowError(+ f"Qualtrics export exceeded the {MAX_DOWNLOAD_SECONDS}s download budget; aborting"+ )+ if not chunk:+ continue+ total += len(chunk)+ if total > MAX_EXPORT_ARCHIVE_BYTES:+ raise QualtricsResponseTooLargeError(+ f"Qualtrics export exceeded the {MAX_EXPORT_ARCHIVE_BYTES}-byte archive limit"+ )+ buffer.write(chunk)+ finally:+ response.close()++ # One budget for the whole download so multi-member archives can't bypass the cap.+ budget = _DecompressionBudget(MAX_EXPORT_DECOMPRESSED_BYTES)++ buffer.seek(0)+ if buffer.read(4) != b"PK\x03\x04":+ buffer.seek(0)+ yield from _iter_ndjson(buffer, budget)+ return++ _guard_zip_central_directory(buffer)+ buffer.seek(0)+ with zipfile.ZipFile(buffer) as archive:+ for info in archive.infolist():+ if info.is_dir():+ continue+ with archive.open(info) as member:+ yield from _iter_ndjson(member, budget)+++def _normalize_response_row(survey_id: str, row: dict[str, Any]) -> dict[str, Any]:+ """Flatten one exported response into a stable, survey-independent column set.++ Every survey answers different questions, so `values`/`labels`/`displayedValues` carry a+ different key set per survey. They're stored as JSON text: a struct column would otherwise+ have to reconcile every survey's question set in one table.+ """+ raw_values = row.get("values")+ values: dict[str, Any] = raw_values if isinstance(raw_values, dict) else {}+ return {+ "responseId": row.get("responseId") or values.get("_recordId"),+ "surveyId": survey_id,+ "recordedDate": values.get("recordedDate"),+ "startDate": values.get("startDate"),+ "endDate": values.get("endDate"),+ "status": values.get("status"),+ "progress": values.get("progress"),+ "duration": values.get("duration"),+ "finished": values.get("finished"),+ "distributionChannel": values.get("distributionChannel"),+ "userLanguage": values.get("userLanguage"),+ "values": json.dumps(values),+ "labels": json.dumps(row.get("labels") or {}),+ "displayedFields": json.dumps(row.get("displayedFields") or []),+ "displayedValues": json.dumps(row.get("displayedValues") or {}),+ }+++def _approx_row_bytes(row: dict[str, Any]) -> int:+ """Rough in-memory size of a normalized row, dominated by its JSON-encoded blob columns."""+ return sum(len(row[key]) for key in ("values", "labels", "displayedFields", "displayedValues"))+++def _export_responses(+ client: QualtricsClient,+ survey_id: str,+ start_date: str | None,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Run one survey through the async export: create the job, poll it, stream the file."""+ export_url = client.url(f"/surveys/{survey_id}/export-responses")+ body: dict[str, Any] = {"format": "ndjson", "compress": True}+ if start_date:+ body["startDate"] = start_date++ created = client.post_json(export_url, body)+ progress_id = _result(created).get("progressId")+ if not progress_id:+ raise QualtricsExportFailedError(f"{EXPORT_FAILED_ERROR}: no progressId returned for survey {survey_id}")++ deadline = time.monotonic() + MAX_EXPORT_POLL_SECONDS+ file_id: str | None = None+ while True:+ progress = _result(client.get_json(f"{export_url}/{progress_id}"))+ status = progress.get("status")+ if status == "complete":+ file_id = progress.get("fileId")+ break+ if status == "failed":+ raise QualtricsExportFailedError(f"{EXPORT_FAILED_ERROR}: survey {survey_id} reported status 'failed'")+ if time.monotonic() > deadline:+ raise QualtricsExportFailedError(+ f"{EXPORT_FAILED_ERROR}: survey {survey_id} did not finish within {MAX_EXPORT_POLL_SECONDS}s"+ )+ logger.debug(f"Qualtrics: export for {survey_id} at {progress.get('percentComplete')}%")+ time.sleep(EXPORT_POLL_INTERVAL_SECONDS)++ if not file_id:+ raise QualtricsExportFailedError(f"{EXPORT_FAILED_ERROR}: survey {survey_id} completed without a fileId")++ download_url = f"{export_url}/{file_id}/file"+ response = client.get(download_url)+ try:+ _guard_response(response, download_url, logger)+ except Exception:+ response.close()+ raise++ batch: list[dict[str, Any]] = []+ batch_bytes = 0+ for row in _iter_export_file(response):+ normalized = _normalize_response_row(survey_id, row)+ batch.append(normalized)+ batch_bytes += _approx_row_bytes(normalized)+ # Flush on either bound so a run of large rows can't outgrow memory before the count limit.+ if len(batch) >= EXPORT_BATCH_SIZE or batch_bytes >= MAX_EXPORT_BATCH_BYTES:+ yield batch+ batch = []+ batch_bytes = 0+ if batch:+ yield batch+++def get_rows(+ host: str,+ credentials: QualtricsCredentials,+ endpoint: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[QualtricsResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = QUALTRICS_ENDPOINTS[endpoint]++ # Re-check at run time (not just at source-create) in case the host was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ raise QualtricsHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ client = QualtricsClient(host, credentials, api_version, logger)+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if not config.fans_out_over_surveys:+ yield from _iter_collection(+ client,+ client.url(config.path),+ resumable_source_manager,+ start_url=resume.next_page if resume else None,+ )+ return++ survey_ids = _survey_ids(client)+ start_index = resume.parent_index if resume else 0+ if start_index:+ logger.debug(f"Qualtrics: resuming {endpoint} from survey {start_index} of {len(survey_ids)}")++ start_date = (+ format_incremental_value(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value is not None+ else None+ )++ for index in range(start_index, len(survey_ids)):+ survey_id = survey_ids[index]+ yield from _rows_for_survey(client, config, survey_id, start_date, logger)+ # Saved AFTER the survey's rows are yielded, so a crash replays that survey instead+ # of skipping it — merge dedupes on the composite primary key.+ resumable_source_manager.save_state(QualtricsResumeConfig(parent_index=index + 1))+++def _rows_for_survey(+ client: QualtricsClient,+ config: QualtricsEndpointConfig,+ survey_id: str,+ start_date: str | None,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ if config.fetch_mode == "survey_export":+ yield from _export_responses(client, survey_id, start_date, logger)+ return++ if config.fetch_mode == "survey_query":+ url = client.url(config.path, {"surveyId": survey_id})+ for page in _iter_collection(client, url, resumable_source_manager=None):+ yield [{**row, "surveyId": survey_id} for row in page]+ return++ payload = client.get_json(client.url(config.path.format(survey_id=survey_id)))+ elements = _elements(payload)+ if elements:+ yield [{**row, "surveyId": survey_id} for row in elements]+++def validate_credentials(+ datacenter_id: str,+ credentials: QualtricsCredentials,+ api_version: str,+ schema_name: Optional[str] = None,+ team_id: Optional[int] = None,+) -> tuple[bool, str | None]:+ """Confirm the credentials are genuine, and (when scoped) that the endpoint is reachable.++ Qualtrics grants permissions per resource, so at source-create a working `whoami` is+ enough — a user may legitimately lack access to endpoints they never intend to sync. A+ scoped probe additionally requests that endpoint and treats 403 as a hard failure.+ """+ try:+ host = validate_host(datacenter_id)+ except QualtricsConfigurationError as e:+ return False, str(e)++ # The host is customer-supplied, so block ones resolving to private/internal addresses.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(host, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ client = QualtricsClient(host, credentials, api_version)++ probe_path = VALIDATION_PATHS.get(schema_name or "", "/whoami")+ try:+ client.get_json(client.url(probe_path))+ except QualtricsConfigurationError as e:+ return False, str(e)+ except QualtricsHostNotAllowedError:+ return False, HOST_NOT_ALLOWED_ERROR+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status == 401:+ return False, "Invalid Qualtrics credentials"+ if status == 403:+ if schema_name is None:+ # A valid credential that can't read `whoami` is still valid; scope problems+ # surface per table rather than blocking the whole source.+ return True, None+ return False, f"Your Qualtrics credentials lack permission to read {schema_name}"+ return False, str(e)+ except (QualtricsRetryableError, requests.exceptions.RequestException) as e:+ return False, str(e)++ return True, None+++def qualtrics_source(+ datacenter_id: str,+ credentials: QualtricsCredentials,+ endpoint: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[QualtricsResumeConfig],+ team_id: int,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = QUALTRICS_ENDPOINTS[endpoint]+ host = validate_host(datacenter_id)++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ host=host,+ credentials=credentials,+ endpoint=endpoint,+ api_version=api_version,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_key,+ 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,+ # Fan-out endpoints arrive grouped by survey, not globally ascending by the cursor —+ # `desc` defers the watermark to the end of the run instead of advancing it past+ # surveys a crashed run still owes.+ sort_mode="desc" if config.fans_out_over_surveys else "asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/settings.pynew file mode 100644index 000000000000..f566a3382320--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/settings.py@@ -0,0 +1,97 @@+from dataclasses import dataclass, field+from typing import Literal++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Qualtrics serves every brand from a datacenter-specific host; the API version is a path+# segment under it (`https://{datacenter}.qualtrics.com/API/v3`).+QUALTRICS_API_VERSION = "v3"+QUALTRICS_DEFAULT_DOMAIN_SUFFIX = ".qualtrics.com"++# How an endpoint reaches its rows.+# "list" — a brand-wide paginated collection under `result.elements`+# "survey_query" — the same collection shape, filtered per survey via a `surveyId` param+# "survey_path" — one un-paginated `result.elements` payload per survey, keyed in the path+# "survey_export" — the async response-export pipeline (create job -> poll -> download zip)+FetchMode = Literal["list", "survey_query", "survey_path", "survey_export"]+++@dataclass(frozen=True)+class QualtricsEndpointConfig:+ name: str+ # Path under `/API/{version}`. `{survey_id}` is substituted per parent survey.+ path: str+ primary_key: list[str]+ fetch_mode: FetchMode = "list"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field, never a `lastModified`-style column that would rewrite+ # partitions on every sync.+ partition_key: str | None = None++ @property+ def fans_out_over_surveys(self) -> bool:+ return self.fetch_mode != "list"+++RECORDED_DATE_INCREMENTAL = incremental_field("recordedDate")++QUALTRICS_ENDPOINTS: dict[str, QualtricsEndpointConfig] = {+ "surveys": QualtricsEndpointConfig(+ name="surveys",+ path="/surveys",+ primary_key=["id"],+ # `lastModified` is returned but Qualtrics exposes no modified-since filter on the+ # collection, so a cursor here would still walk every page — full refresh only.+ partition_key="creationDate",+ ),+ "users": QualtricsEndpointConfig(+ name="users",+ path="/users",+ primary_key=["id"],+ ),+ "groups": QualtricsEndpointConfig(+ name="groups",+ path="/groups",+ primary_key=["id"],+ ),+ "divisions": QualtricsEndpointConfig(+ name="divisions",+ path="/divisions",+ primary_key=["divisionId"],+ ),+ "distributions": QualtricsEndpointConfig(+ name="distributions",+ path="/distributions",+ # Distributions are listed per survey, so the survey id is part of the row identity.+ primary_key=["surveyId", "id"],+ fetch_mode="survey_query",+ ),+ "survey_questions": QualtricsEndpointConfig(+ name="survey_questions",+ path="/survey-definitions/{survey_id}/questions",+ primary_key=["surveyId", "QuestionID"],+ fetch_mode="survey_path",+ ),+ "survey_responses": QualtricsEndpointConfig(+ name="survey_responses",+ path="/surveys/{survey_id}/export-responses",+ primary_key=["surveyId", "responseId"],+ fetch_mode="survey_export",+ # `startDate` on the export request filters server-side on `recordedDate`.+ incremental_fields=[RECORDED_DATE_INCREMENTAL],+ partition_key="recordedDate",+ ),+}++ENDPOINTS = tuple(QUALTRICS_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in QUALTRICS_ENDPOINTS.items()+}++# Endpoint probed during per-schema credential validation. Fan-out endpoints have no reachable+# URL without a survey id, so they validate through the survey list instead.+VALIDATION_PATHS: dict[str, str] = {+ name: "/surveys" if config.fans_out_over_surveys else config.path for name, config in QUALTRICS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/source.pyindex 07ac3b2a67ce..6fd847710171 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/source.py@@ -1,32 +1,229 @@-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.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 (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.qualtrics import (QualtricsSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.qualtrics.qualtrics import (+ EXPORT_FAILED_ERROR,+ HOST_NOT_ALLOWED_ERROR,+ INCOMPLETE_CREDENTIALS_ERROR,+ QualtricsCredentials,+ QualtricsResumeConfig,+ qualtrics_source,+ validate_credentials as validate_qualtrics_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.qualtrics.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ QUALTRICS_API_VERSION,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _credentials_from_config(config: QualtricsSourceConfig) -> QualtricsCredentials:+ auth = config.auth_method+ if auth.selection == "oauth_client_credentials":+ return QualtricsCredentials(+ method="oauth_client_credentials",+ client_id=auth.client_id,+ client_secret=auth.client_secret,+ )+ return QualtricsCredentials(method="api_token", api_token=auth.api_token)++@SourceRegistry.register-class QualtricsSource(SimpleSource[QualtricsSourceConfig]):+class QualtricsSource(ResumableSource[QualtricsSourceConfig, QualtricsResumeConfig]):+ supported_versions = (QUALTRICS_API_VERSION,)+ default_version = QUALTRICS_API_VERSION+ api_docs_url = "https://api.qualtrics.com/"++ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.QUALTRICS+ @property+ def connection_host_fields(self) -> list[str]:+ # `datacenter_id` decides which host the stored credentials are sent to, so retargeting+ # it must re-require them.+ return ["datacenter_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.QUALTRICS,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Qualtrics",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["surveys", "xm", "experience management"],+ caption="""Enter your Qualtrics datacenter ID and credentials to pull surveys, responses and account metadata into the PostHog Data warehouse.++Find your datacenter ID under **Account settings > Qualtrics IDs**. It looks like `iad1` or `fra1`. If your brand uses a custom domain, paste the full hostname instead.++The quickest way to connect is an API token from **Account settings > Qualtrics IDs**. The Qualtrics user needs the "Access API" permission plus read access to the surveys, users, groups, divisions and distributions you want to sync.++You can also connect with an OAuth client: create one under **Account settings > Qualtrics IDs**, pick the client credentials grant, and give it read access to surveys, survey responses, survey definitions, users, groups, divisions and distributions.++Survey responses sync incrementally on `recordedDate`. Every other table is a full refresh, because Qualtrics has no modified-since filter on its collection endpoints.+""",iconPath="/static/services/qualtrics.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/qualtrics",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="datacenter_id",+ label="Datacenter ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="iad1",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="auth_method",+ label="Authentication method",+ required=True,+ defaultValue="api_token",+ options=[+ SourceFieldSelectConfigOption(+ label="API token",+ value="api_token",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="OAuth client credentials",+ value="oauth_client_credentials",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="client_id",+ label="Client ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="client_secret",+ label="Client secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.qualtrics.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid or expired Qualtrics credentials. Please re-enter them and reconnect.",+ "403 Client Error": "Your Qualtrics credentials lack permission for this data. Grant the user or OAuth client read access and try again.",+ HOST_NOT_ALLOWED_ERROR: "The Qualtrics host is not allowed. Please use your brand's datacenter ID.",+ INCOMPLETE_CREDENTIALS_ERROR: "Qualtrics credentials are incomplete. Please re-enter them and reconnect.",+ EXPORT_FAILED_ERROR: "Qualtrics could not build the response export. Please check the survey and try again.",+ }++ def get_schemas(+ self,+ config: QualtricsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ # A response can be restated (a partial response finished later is re-exported+ # under the same id), so merge is the only safe incremental mode.+ merge_only=("survey_responses",),+ )++ def validate_credentials(+ self,+ config: QualtricsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_qualtrics_credentials(+ datacenter_id=config.datacenter_id,+ credentials=_credentials_from_config(config),+ api_version=self.resolve_api_version(api_version),+ schema_name=schema_name,+ team_id=team_id,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[QualtricsResumeConfig]:+ return ResumableSourceManager[QualtricsResumeConfig](inputs, QualtricsResumeConfig)++ def source_for_pipeline(+ self,+ config: QualtricsSourceConfig,+ resumable_source_manager: ResumableSourceManager[QualtricsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return qualtrics_source(+ datacenter_id=config.datacenter_id,+ credentials=_credentials_from_config(config),+ endpoint=inputs.schema_name,+ api_version=self.resolve_api_version(inputs.api_version),+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ 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/qualtrics/tests/test_qualtrics.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/tests/test_qualtrics.pynew file mode 100644index 000000000000..ae470a97e672--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/tests/test_qualtrics.py@@ -0,0 +1,686 @@+import io+import json+import zipfile+from collections.abc import Iterable, Iterator+from datetime import UTC, date, datetime+from typing import Any, cast++import pytest+from unittest import mock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.qualtrics import qualtrics as qualtrics_module+from products.warehouse_sources.backend.temporal.data_imports.sources.qualtrics.qualtrics import (+ EXPORT_FAILED_ERROR,+ QualtricsAuthManager,+ QualtricsClient,+ QualtricsConfigurationError,+ QualtricsCredentials,+ QualtricsExportFailedError,+ QualtricsHostNotAllowedError,+ QualtricsPaginationLimitError,+ QualtricsResponseTooLargeError,+ QualtricsResumeConfig,+ QualtricsRetryableError,+ _guard_response,+ _iter_export_file,+ _normalize_response_row,+ _read_capped,+ format_incremental_value,+ get_rows,+ normalize_host,+ qualtrics_source,+ validate_credentials,+ validate_host,+)++HOST = "iad1.qualtrics.com"+BASE = f"https://{HOST}/API/v3"+API_TOKEN_CREDENTIALS = QualtricsCredentials(method="api_token", api_token="tok-123")+OAUTH_CREDENTIALS = QualtricsCredentials(method="oauth_client_credentials", client_id="client", client_secret="shhh")+++class FakeResumeManager(ResumableSourceManager[QualtricsResumeConfig]):+ def __init__(self, state: QualtricsResumeConfig | None = None) -> None:+ self.state = state+ self.saved: list[QualtricsResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> QualtricsResumeConfig | None:+ return self.state++ def save_state(self, data: QualtricsResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.state = None+++def _response(*, status_code: int = 200, json_data: Any = None, body: bytes | None = None) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ response.is_redirect = status_code in (302, 303, 307)+ response.is_permanent_redirect = status_code in (301, 308)+ payload = body if body is not None else (json.dumps(json_data).encode() if json_data is not None else b"")+ # Bodies are read with stream=True + iter_content, so serve them in that shape. A fresh+ # iterator per call lets one mock response stand in for repeated reads.+ response.iter_content.side_effect = lambda *args, **kwargs: iter([payload] if payload else [])+ if status_code >= 400:+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: for url: {BASE}", response=response+ )+ return response+++def _collection(elements: list[dict[str, Any]], next_page: str | None = None) -> dict[str, Any]:+ return {"result": {"elements": elements, "nextPage": next_page}, "meta": {"httpStatus": "200 - OK"}}+++def _session(get_responses: list[Any] | None = None, post_responses: list[Any] | None = None) -> mock.MagicMock:+ session = mock.MagicMock()+ if get_responses is not None:+ session.get.side_effect = get_responses+ if post_responses is not None:+ session.post.side_effect = post_responses+ return session+++def _zip_bytes(name: str, content: str) -> bytes:+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:+ archive.writestr(name, content)+ return buffer.getvalue()+++def _multi_member_zip_bytes(members: dict[str, str]) -> bytes:+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:+ for name, content in members.items():+ archive.writestr(name, content)+ return buffer.getvalue()+++def _zip_with_spoofed_low_member_count(members: dict[str, str]) -> bytes:+ """Append a second EOCD that lies about the member count while keeping the real directory size.++ zipfile selects the trailing EOCD and reads the central directory by its byte length, so a+ guard that trusts the entry-count field would wave this through.+ """+ raw = _multi_member_zip_bytes(members)+ marker = raw.rfind(b"PK\x05\x06")+ spoofed = bytearray(raw[marker:])+ spoofed[8:10] = (1).to_bytes(2, "little") # entries on this disk+ spoofed[10:12] = (1).to_bytes(2, "little") # total entries+ return raw + bytes(spoofed)+++def _run_get_rows(+ endpoint: str,+ session: mock.MagicMock,+ manager: FakeResumeManager,+ **kwargs: Any,+) -> list[list[dict[str, Any]]]:+ with (+ mock.patch.object(qualtrics_module, "make_tracked_session", return_value=session),+ mock.patch.object(qualtrics_module, "_is_host_safe", return_value=(True, None)),+ ):+ return list(+ get_rows(+ host=HOST,+ credentials=API_TOKEN_CREDENTIALS,+ endpoint=endpoint,+ api_version="v3",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ **kwargs,+ )+ )+++class TestQualtricsTransport:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("iad1", "iad1.qualtrics.com"),+ ("IAD1", "iad1.qualtrics.com"),+ (" fra1 ", "fra1.qualtrics.com"),+ ("iad1.qualtrics.com", "iad1.qualtrics.com"),+ ("https://iad1.qualtrics.com", "iad1.qualtrics.com"),+ ("https://iad1.qualtrics.com/API/v3/", "iad1.qualtrics.com"),+ ("surveys.acme.com", "surveys.acme.com"),+ ],+ )+ def test_normalize_host(self, raw: str, expected: str) -> None:+ assert normalize_host(raw) == expected++ @pytest.mark.parametrize("raw", ["", " ", "bad host", "iad1.qualtrics.com:8080", "iad1_@"])+ def test_validate_host_rejects_junk(self, raw: str) -> None:+ with pytest.raises(QualtricsConfigurationError):+ validate_host(raw)++ @pytest.mark.parametrize(+ "value, expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("2026-03-04T00:00:00Z", "2026-03-04T00:00:00Z"),+ ],+ )+ def test_format_incremental_value(self, value: Any, expected: str) -> None:+ assert format_incremental_value(value) == expected++ @pytest.mark.parametrize("status_code", [429, 500, 502, 503])+ def test_guard_response_classifies_retryable(self, status_code: int) -> None:+ with pytest.raises(QualtricsRetryableError):+ _guard_response(_response(status_code=status_code), BASE)++ @pytest.mark.parametrize("status_code", [301, 302, 307, 308])+ def test_guard_response_refuses_redirects(self, status_code: int) -> None:+ with pytest.raises(QualtricsHostNotAllowedError):+ _guard_response(_response(status_code=status_code), BASE)++ @pytest.mark.parametrize("status_code", [400, 401, 403, 404])+ def test_guard_response_raises_for_client_errors(self, status_code: int) -> None:+ with pytest.raises(requests.HTTPError):+ _guard_response(_response(status_code=status_code), BASE)++ def test_read_capped_refuses_oversized_body(self) -> None:+ with pytest.raises(QualtricsResponseTooLargeError):+ _read_capped(_response(body=b"x" * 1024), max_bytes=10)++ def test_api_token_rides_the_header(self) -> None:+ manager = QualtricsAuthManager(_session(), HOST, API_TOKEN_CREDENTIALS)+ assert manager.headers()["X-API-TOKEN"] == "tok-123"++ def test_api_token_missing_is_a_configuration_error(self) -> None:+ manager = QualtricsAuthManager(_session(), HOST, QualtricsCredentials(method="api_token"))+ with pytest.raises(QualtricsConfigurationError):+ manager.headers()++ def test_oauth_token_is_minted_once_and_cached(self) -> None:+ session = _session(post_responses=[_response(json_data={"access_token": "abc", "expires_in": 3600})])+ manager = QualtricsAuthManager(session, HOST, OAUTH_CREDENTIALS)++ assert manager.headers()["Authorization"] == "Bearer abc"+ assert manager.headers()["Authorization"] == "Bearer abc"+ assert session.post.call_count == 1+ assert session.post.call_args.args[0] == f"https://{HOST}/oauth2/token"++ def test_oauth_token_is_reminted_inside_the_refresh_margin(self) -> None:+ # 30s of life is inside TOKEN_REFRESH_MARGIN_SECONDS, so the next request must not+ # ride a token that would expire mid-flight.+ session = _session(+ post_responses=[+ _response(json_data={"access_token": "first", "expires_in": 30}),+ _response(json_data={"access_token": "second", "expires_in": 3600}),+ ]+ )+ manager = QualtricsAuthManager(session, HOST, OAUTH_CREDENTIALS)++ assert manager.headers()["Authorization"] == "Bearer first"+ assert manager.headers()["Authorization"] == "Bearer second"++ def test_oauth_without_client_credentials_is_a_configuration_error(self) -> None:+ manager = QualtricsAuthManager(_session(), HOST, QualtricsCredentials(method="oauth_client_credentials"))+ with pytest.raises(QualtricsConfigurationError):+ manager.headers()++ @pytest.mark.parametrize(+ "url",+ [+ "http://iad1.qualtrics.com/API/v3/surveys",+ "https://evil.example.com/API/v3/surveys",+ "https://169.254.169.254/latest/meta-data",+ ],+ )+ def test_client_refuses_urls_off_the_configured_host(self, url: str) -> None:+ with mock.patch.object(qualtrics_module, "make_tracked_session", return_value=_session()):+ client = QualtricsClient(HOST, API_TOKEN_CREDENTIALS, "v3")+ with pytest.raises(QualtricsHostNotAllowedError):+ client.get_json(url)++ def test_client_builds_versioned_urls(self) -> None:+ with mock.patch.object(qualtrics_module, "make_tracked_session", return_value=_session()):+ client = QualtricsClient(HOST, API_TOKEN_CREDENTIALS, "v3")++ assert client.url("/surveys") == f"{BASE}/surveys"+ assert client.url("/distributions", {"surveyId": "SV_1"}) == f"{BASE}/distributions?surveyId=SV_1"+++class TestCollectionPagination:+ def test_follows_next_page_and_checkpoints_after_each_page(self) -> None:+ page_two = f"{BASE}/users?offset=100"+ session = _session(+ get_responses=[+ _response(json_data=_collection([{"id": "UR_1"}], next_page=page_two)),+ _response(json_data=_collection([{"id": "UR_2"}], next_page=None)),+ ]+ )+ manager = FakeResumeManager()++ batches = _run_get_rows("users", session, manager)++ assert batches == [[{"id": "UR_1"}], [{"id": "UR_2"}]]+ # Checkpointed only after the first page was yielded, and never past the final page.+ assert manager.saved == [QualtricsResumeConfig(next_page=page_two)]++ def test_resumes_from_the_saved_next_page(self) -> None:+ resume_url = f"{BASE}/users?offset=200"+ session = _session(get_responses=[_response(json_data=_collection([{"id": "UR_9"}]))])++ batches = _run_get_rows("users", session, FakeResumeManager(QualtricsResumeConfig(next_page=resume_url)))++ assert batches == [[{"id": "UR_9"}]]+ assert session.get.call_args.args[0] == resume_url++ def test_empty_collection_yields_nothing(self) -> None:+ session = _session(get_responses=[_response(json_data=_collection([]))])++ assert _run_get_rows("groups", session, FakeResumeManager()) == []++ def test_pagination_that_never_terminates_is_capped(self) -> None:+ session = _session()+ session.get.return_value = _response(json_data=_collection([{"id": "UR_1"}], next_page=f"{BASE}/users?p=1"))++ with mock.patch.object(qualtrics_module, "MAX_PAGES", 3), pytest.raises(QualtricsPaginationLimitError):+ _run_get_rows("users", session, FakeResumeManager())+++class TestSurveyFanout:+ def test_query_fanout_stamps_the_parent_survey_id(self) -> None:+ session = _session(+ get_responses=[+ _response(json_data=_collection([{"id": "SV_1"}, {"id": "SV_2"}])),+ _response(json_data=_collection([{"id": "EMD_1"}])),+ _response(json_data=_collection([{"id": "EMD_2"}])),+ ]+ )+ manager = FakeResumeManager()++ batches = _run_get_rows("distributions", session, manager)++ assert batches == [+ [{"id": "EMD_1", "surveyId": "SV_1"}],+ [{"id": "EMD_2", "surveyId": "SV_2"}],+ ]+ assert manager.saved == [QualtricsResumeConfig(parent_index=1), QualtricsResumeConfig(parent_index=2)]++ def test_survey_ids_that_could_steer_the_url_are_dropped(self) -> None:+ session = _session(+ get_responses=[+ _response(json_data=_collection([{"id": "../../oauth2/token"}, {"id": "SV_ok"}])),+ _response(json_data=_collection([{"QuestionID": "QID1"}])),+ ]+ )++ batches = _run_get_rows("survey_questions", session, FakeResumeManager())++ assert batches == [[{"QuestionID": "QID1", "surveyId": "SV_ok"}]]+ assert session.get.call_args_list[1].args[0] == f"{BASE}/survey-definitions/SV_ok/questions"++ def test_over_length_survey_ids_are_dropped(self) -> None:+ session = _session(+ get_responses=[+ _response(json_data=_collection([{"id": "SV_toolong"}, {"id": "SV_ok"}])),+ _response(json_data=_collection([{"QuestionID": "QID1"}])),+ ]+ )++ with mock.patch.object(qualtrics_module, "MAX_SURVEY_ID_LENGTH", 5):+ batches = _run_get_rows("survey_questions", session, FakeResumeManager())++ assert batches == [[{"QuestionID": "QID1", "surveyId": "SV_ok"}]]++ def test_too_many_surveys_is_refused(self) -> None:+ session = _session(get_responses=[_response(json_data=_collection([{"id": "SV_1"}, {"id": "SV_2"}]))])++ with mock.patch.object(qualtrics_module, "MAX_SURVEY_COUNT", 1):+ with pytest.raises(QualtricsResponseTooLargeError):+ _run_get_rows("survey_questions", session, FakeResumeManager())++ def test_path_fanout_stamps_the_parent_survey_id(self) -> None:+ session = _session(+ get_responses=[+ _response(json_data=_collection([{"id": "SV_1"}])),+ _response(json_data=_collection([{"QuestionID": "QID1"}])),+ ]+ )++ batches = _run_get_rows("survey_questions", session, FakeResumeManager())++ assert batches == [[{"QuestionID": "QID1", "surveyId": "SV_1"}]]+ assert session.get.call_args_list[1].args[0] == f"{BASE}/survey-definitions/SV_1/questions"++ def test_resumes_after_the_last_completed_survey(self) -> None:+ session = _session(+ get_responses=[+ _response(json_data=_collection([{"id": "SV_1"}, {"id": "SV_2"}, {"id": "SV_3"}])),+ _response(json_data=_collection([{"QuestionID": "QID9"}])),+ ]+ )+ manager = FakeResumeManager(QualtricsResumeConfig(parent_index=2))++ batches = _run_get_rows("survey_questions", session, manager)++ assert batches == [[{"QuestionID": "QID9", "surveyId": "SV_3"}]]+ assert session.get.call_args_list[1].args[0] == f"{BASE}/survey-definitions/SV_3/questions"+ assert manager.saved == [QualtricsResumeConfig(parent_index=3)]+++class TestResponseExport:+ NDJSON = "\n".join(+ [+ json.dumps(+ {+ "responseId": "R_1",+ "values": {"recordedDate": "2026-01-02T03:04:05Z", "finished": 1, "QID1": 3},+ "labels": {"QID1": "Often"},+ "displayedFields": ["QID1"],+ "displayedValues": {"QID1": [1, 2, 3]},+ }+ ),+ json.dumps({"responseId": "R_2", "values": {"recordedDate": "2026-01-03T03:04:05Z"}}),+ ]+ )++ def _export_session(self, file_body: bytes, start_date_capture: list[Any] | None = None) -> mock.MagicMock:+ session = _session(+ get_responses=[+ _response(json_data=_collection([{"id": "SV_1"}])),+ _response(json_data={"result": {"status": "inProgress", "percentComplete": 12.5}}),+ _response(json_data={"result": {"status": "complete", "fileId": "FID_1"}}),+ _response(body=file_body),+ ],+ post_responses=[_response(json_data={"result": {"progressId": "PID_1"}})],+ )+ if start_date_capture is not None:+ original = session.post.side_effect++ def _capture(url: str, **kwargs: Any) -> Any:+ start_date_capture.append(kwargs.get("json"))+ return next(iter(original))++ session.post.side_effect = _capture+ return session++ def _run(self, session: mock.MagicMock, **kwargs: Any) -> list[list[dict[str, Any]]]:+ with mock.patch.object(qualtrics_module, "EXPORT_POLL_INTERVAL_SECONDS", 0):+ return _run_get_rows("survey_responses", session, FakeResumeManager(), **kwargs)++ def test_polls_until_complete_then_streams_the_zipped_export(self) -> None:+ batches = self._run(self._export_session(_zip_bytes("responses.ndjson", self.NDJSON)))++ assert len(batches) == 1+ rows = batches[0]+ assert [row["responseId"] for row in rows] == ["R_1", "R_2"]+ assert rows[0]["surveyId"] == "SV_1"+ assert rows[0]["recordedDate"] == "2026-01-02T03:04:05Z"+ assert json.loads(rows[0]["labels"]) == {"QID1": "Often"}++ def test_an_uncompressed_export_body_is_parsed_directly(self) -> None:+ batches = self._run(self._export_session(self.NDJSON.encode()))++ assert [row["responseId"] for row in batches[0]] == ["R_1", "R_2"]++ def test_incremental_runs_send_the_watermark_as_start_date(self) -> None:+ captured: list[Any] = []+ session = self._export_session(_zip_bytes("responses.ndjson", self.NDJSON), start_date_capture=captured)++ self._run(+ session,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )++ assert captured == [{"format": "ndjson", "compress": True, "startDate": "2026-01-01T00:00:00Z"}]++ def test_full_refresh_runs_send_no_start_date(self) -> None:+ captured: list[Any] = []+ session = self._export_session(_zip_bytes("responses.ndjson", self.NDJSON), start_date_capture=captured)++ self._run(session)++ assert captured == [{"format": "ndjson", "compress": True}]++ @pytest.mark.parametrize(+ "progress_payload",+ [+ {"result": {"status": "failed"}},+ {"result": {"status": "complete"}},+ ],+ )+ def test_a_broken_export_job_fails_permanently(self, progress_payload: dict[str, Any]) -> None:+ session = _session(+ get_responses=[+ _response(json_data=_collection([{"id": "SV_1"}])),+ _response(json_data=progress_payload),+ ],+ post_responses=[_response(json_data={"result": {"progressId": "PID_1"}})],+ )++ with pytest.raises(QualtricsExportFailedError, match=EXPORT_FAILED_ERROR):+ self._run(session)++ def test_a_missing_progress_id_fails_permanently(self) -> None:+ session = _session(+ get_responses=[_response(json_data=_collection([{"id": "SV_1"}]))],+ post_responses=[_response(json_data={"result": {}})],+ )++ with pytest.raises(QualtricsExportFailedError, match=EXPORT_FAILED_ERROR):+ self._run(session)++ def test_export_rows_are_batched(self) -> None:+ many = "\n".join(json.dumps({"responseId": f"R_{i}", "values": {}}) for i in range(5))+ session = self._export_session(_zip_bytes("responses.ndjson", many))++ with mock.patch.object(qualtrics_module, "EXPORT_BATCH_SIZE", 2):+ batches = self._run(session)++ assert [len(batch) for batch in batches] == [2, 2, 1]++ def test_blank_lines_in_the_export_are_skipped(self) -> None:+ body = f"\n{self.NDJSON}\n\n"+ rows: list[dict[str, Any]] = list(_iter_export_file(_response(body=body.encode())))++ assert [row["responseId"] for row in rows] == ["R_1", "R_2"]++ def test_decompressed_export_is_capped(self) -> None:+ with mock.patch.object(qualtrics_module, "MAX_EXPORT_DECOMPRESSED_BYTES", 4):+ with pytest.raises(QualtricsResponseTooLargeError):+ list(_iter_export_file(_response(body=_zip_bytes("r.ndjson", self.NDJSON))))++ def test_decompressed_cap_is_shared_across_archive_members(self) -> None:+ # Each member stays under the cap; only their aggregate exceeds it, so a per-member+ # counter would let the archive through.+ body = _multi_member_zip_bytes({"a.ndjson": self.NDJSON, "b.ndjson": self.NDJSON})+ with mock.patch.object(qualtrics_module, "MAX_EXPORT_DECOMPRESSED_BYTES", len(self.NDJSON) + 5):+ with pytest.raises(QualtricsResponseTooLargeError):+ list(_iter_export_file(_response(body=body)))++ def test_archive_with_too_many_members_is_refused(self) -> None:+ # The central-directory byte length is rejected before zipfile builds a ZipInfo per+ # entry, so a crafted many-membered archive can't exhaust memory first.+ body = _multi_member_zip_bytes({f"m_{i}.ndjson": self.NDJSON for i in range(3)})+ with mock.patch.object(qualtrics_module, "MAX_EXPORT_ARCHIVE_MEMBERS", 2):+ with pytest.raises(QualtricsResponseTooLargeError):+ list(_iter_export_file(_response(body=body)))++ def test_archive_with_spoofed_low_member_count_is_refused(self) -> None:+ # A trailing EOCD claiming one member can't hide a large central directory: the guard+ # bounds the directory's byte length, which is what zipfile actually reads.+ body = _zip_with_spoofed_low_member_count({f"m_{i}.ndjson": self.NDJSON for i in range(3)})+ with mock.patch.object(qualtrics_module, "MAX_EXPORT_ARCHIVE_MEMBERS", 2):+ with pytest.raises(QualtricsResponseTooLargeError):+ list(_iter_export_file(_response(body=body)))++ def test_export_batches_flush_on_accumulated_bytes(self) -> None:+ rows = "\n".join(json.dumps({"responseId": f"R_{i}", "values": {"blob": "x" * 500}}) for i in range(3))+ session = self._export_session(_zip_bytes("responses.ndjson", rows))++ with mock.patch.object(qualtrics_module, "MAX_EXPORT_BATCH_BYTES", 400):+ batches = self._run(session)++ # Each row's blob column alone exceeds the byte cap, so batches flush per row despite the+ # far larger row-count batch size.+ assert [len(batch) for batch in batches] == [1, 1, 1]+++class TestNormalizeResponseRow:+ def test_flattens_values_and_json_encodes_the_survey_specific_blobs(self) -> None:+ row = _normalize_response_row(+ "SV_1",+ {+ "responseId": "R_1",+ "values": {+ "recordedDate": "2026-01-02T03:04:05Z",+ "startDate": "2026-01-02T03:00:00Z",+ "progress": 100,+ "duration": 42,+ "finished": 1,+ "QID1": 3,+ },+ "labels": {"QID1": "Often"},+ },+ )++ assert row["surveyId"] == "SV_1"+ assert row["responseId"] == "R_1"+ assert row["progress"] == 100+ assert json.loads(row["values"])["QID1"] == 3+ assert json.loads(row["displayedFields"]) == []++ def test_falls_back_to_the_record_id_when_the_response_id_is_absent(self) -> None:+ row = _normalize_response_row("SV_1", {"values": {"_recordId": "R_7"}})++ assert row["responseId"] == "R_7"+++class TestValidateCredentials:+ def _validate(self, response: mock.MagicMock, schema_name: str | None = None) -> tuple[bool, str | None]:+ with (+ mock.patch.object(qualtrics_module, "make_tracked_session", return_value=_session([response])),+ mock.patch.object(qualtrics_module, "_is_host_safe", return_value=(True, None)),+ ):+ return validate_credentials("iad1", API_TOKEN_CREDENTIALS, "v3", schema_name, team_id=1)++ def test_a_working_token_validates(self) -> None:+ assert self._validate(_response(json_data={"result": {"brandId": "acme"}})) == (True, None)++ def test_an_invalid_token_is_rejected(self) -> None:+ valid, error = self._validate(_response(status_code=401))+ assert valid is False+ assert error == "Invalid Qualtrics credentials"++ def test_a_403_at_source_create_still_validates(self) -> None:+ # Qualtrics grants permissions per resource, so a user who can't read one endpoint+ # must still be able to connect and sync the ones they can.+ assert self._validate(_response(status_code=403)) == (True, None)++ def test_a_403_on_a_scoped_probe_is_rejected(self) -> None:+ valid, error = self._validate(_response(status_code=403), schema_name="users")+ assert valid is False+ assert error is not None and "users" in error++ @pytest.mark.parametrize("datacenter_id", ["", " ", "not a host", "iad1.qualtrics.com:8080", "iad1@evil"])+ def test_an_invalid_datacenter_id_is_rejected_before_any_request(self, datacenter_id: str) -> None:+ with mock.patch.object(qualtrics_module, "make_tracked_session") as session_factory:+ valid, error = validate_credentials(datacenter_id, API_TOKEN_CREDENTIALS, "v3", None, team_id=1)++ assert (valid, error) == (False, "Invalid Qualtrics datacenter ID")+ assert session_factory.call_count == 0++ def test_a_blocked_host_is_rejected(self) -> None:+ with mock.patch.object(qualtrics_module, "_is_host_safe", return_value=(False, "nope")):+ valid, error = validate_credentials("iad1", API_TOKEN_CREDENTIALS, "v3", None, team_id=1)+ assert (valid, error) == (False, "nope")++ def test_fanout_endpoints_probe_the_survey_list(self) -> None:+ session = _session([_response(json_data=_collection([]))])+ with (+ mock.patch.object(qualtrics_module, "make_tracked_session", return_value=session),+ mock.patch.object(qualtrics_module, "_is_host_safe", return_value=(True, None)),+ ):+ validate_credentials("iad1", API_TOKEN_CREDENTIALS, "v3", "survey_responses", team_id=1)++ assert session.get.call_args.args[0] == f"{BASE}/surveys"+++class TestSourceResponse:+ @pytest.mark.parametrize(+ "endpoint, primary_keys, sort_mode, partition_keys",+ [+ ("surveys", ["id"], "asc", ["creationDate"]),+ ("users", ["id"], "asc", None),+ ("groups", ["id"], "asc", None),+ ("divisions", ["divisionId"], "asc", None),+ ("distributions", ["surveyId", "id"], "desc", None),+ ("survey_questions", ["surveyId", "QuestionID"], "desc", None),+ ("survey_responses", ["surveyId", "responseId"], "desc", ["recordedDate"]),+ ],+ )+ def test_response_shape_per_endpoint(+ self,+ endpoint: str,+ primary_keys: list[str],+ sort_mode: str,+ partition_keys: list[str] | None,+ ) -> None:+ response = qualtrics_source(+ datacenter_id="iad1",+ credentials=API_TOKEN_CREDENTIALS,+ endpoint=endpoint,+ api_version="v3",+ logger=mock.MagicMock(),+ resumable_source_manager=FakeResumeManager(),+ team_id=1,+ )++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == sort_mode+ assert response.partition_keys == partition_keys+ assert response.partition_mode == ("datetime" if partition_keys else None)++ def test_items_are_lazy_so_no_request_happens_until_iterated(self) -> None:+ session = _session(get_responses=[_response(json_data=_collection([{"id": "UR_1"}]))])+ response = qualtrics_source(+ datacenter_id="iad1",+ credentials=API_TOKEN_CREDENTIALS,+ endpoint="users",+ api_version="v3",+ logger=mock.MagicMock(),+ resumable_source_manager=FakeResumeManager(),+ team_id=1,+ )++ assert session.get.call_count == 0++ with (+ mock.patch.object(qualtrics_module, "make_tracked_session", return_value=session),+ mock.patch.object(qualtrics_module, "_is_host_safe", return_value=(True, None)),+ ):+ items: Iterator[Any] = iter(cast("Iterable[Any]", response.items()))+ assert next(items) == [{"id": "UR_1"}]++ def test_an_unsafe_host_stops_the_sync(self) -> None:+ response = qualtrics_source(+ datacenter_id="iad1",+ credentials=API_TOKEN_CREDENTIALS,+ endpoint="users",+ api_version="v3",+ logger=mock.MagicMock(),+ resumable_source_manager=FakeResumeManager(),+ team_id=1,+ )++ with mock.patch.object(qualtrics_module, "_is_host_safe", return_value=(False, "blocked")):+ with pytest.raises(QualtricsHostNotAllowedError):+ list(cast("Iterable[Any]", response.items()))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/tests/test_qualtrics_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/tests/test_qualtrics_source.pynew file mode 100644index 000000000000..af9bda308620--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/tests/test_qualtrics_source.py@@ -0,0 +1,210 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.qualtrics import (+ QualtricsAuthMethodConfig,+ QualtricsSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.qualtrics import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.qualtrics.qualtrics import (+ QualtricsCredentials,+ QualtricsResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++EXPECTED_ENDPOINTS = {+ "surveys",+ "users",+ "groups",+ "divisions",+ "distributions",+ "survey_questions",+ "survey_responses",+}+++def _config(selection: str = "api_token") -> QualtricsSourceConfig:+ return QualtricsSourceConfig(+ datacenter_id="iad1",+ auth_method=QualtricsAuthMethodConfig(+ selection=selection, # type: ignore[arg-type]+ api_token="tok-123",+ client_id="client",+ client_secret="shhh",+ ),+ )+++def _inputs(schema_name: str = "surveys", **kwargs: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(kwargs)+ return SourceInputs(**defaults)+++def _field_names(fields: list[FieldType]) -> list[str]:+ return [field.name for field in fields]+++class TestQualtricsSource:+ def setup_method(self) -> None:+ self.source = source_module.QualtricsSource()++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.QUALTRICS++ def test_source_is_released_as_alpha(self) -> None:+ config = self.source.get_source_config++ # A finished source must be visible; `unreleasedSource` hides it from users entirely.+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_source_config_collects_a_host_and_both_auth_methods(self) -> None:+ fields = self.source.get_source_config.fields++ assert _field_names(fields) == ["datacenter_id", "auth_method"]+ datacenter, auth = fields+ assert isinstance(datacenter, SourceFieldInputConfig)+ assert datacenter.required is True+ assert isinstance(auth, SourceFieldSelectConfig)+ assert [option.value for option in auth.options] == ["api_token", "oauth_client_credentials"]++ def test_secret_fields_are_marked_secret(self) -> None:+ auth = self.source.get_source_config.fields[1]+ assert isinstance(auth, SourceFieldSelectConfig)+ secrets = {+ field.name: field.secret+ for option in auth.options+ for field in (option.fields or [])+ if isinstance(field, SourceFieldInputConfig)+ }++ assert secrets == {"api_token": True, "client_id": False, "client_secret": True}++ def test_retargeting_the_host_re_requires_credentials(self) -> None:+ assert self.source.connection_host_fields == ["datacenter_id"]++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=1)++ assert {schema.name for schema in schemas} == EXPECTED_ENDPOINTS++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(_config(), team_id=1, names=["surveys"])++ assert [schema.name for schema in schemas] == ["surveys"]++ def test_only_responses_sync_incrementally(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(_config(), team_id=1)}++ responses = schemas["survey_responses"]+ assert responses.supports_incremental is True+ # Exported responses can be restated under the same id, so append would duplicate them.+ assert responses.supports_append is False+ assert [field["field"] for field in responses.incremental_fields] == ["recordedDate"]+ assert all(not schemas[name].supports_incremental for name in EXPECTED_ENDPOINTS - {"survey_responses"})++ def test_tables_are_listed_for_public_docs(self) -> None:+ # `get_schemas` does no I/O, so the docs endpoint can render the catalog credential-free.+ assert self.source.lists_tables_without_credentials is True+ assert {table["name"] for table in self.source.get_documented_tables()} == EXPECTED_ENDPOINTS++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ assert set(self.source.get_canonical_descriptions()) == EXPECTED_ENDPOINTS++ def test_auth_and_permission_errors_are_non_retryable(self) -> None:+ errors = self.source.get_non_retryable_errors()++ assert "401 Client Error" in errors+ assert "403 Client Error" in errors+ assert all(message for message in errors.values())++ def test_api_version_is_pinned_to_the_path_the_code_calls(self) -> None:+ assert self.source.supported_versions == ("v3",)+ assert self.source.default_version == "v3"+ assert self.source.resolve_api_version(None) == "v3"++ @pytest.mark.parametrize(+ "selection, expected",+ [+ ("api_token", QualtricsCredentials(method="api_token", api_token="tok-123")),+ (+ "oauth_client_credentials",+ QualtricsCredentials(method="oauth_client_credentials", client_id="client", client_secret="shhh"),+ ),+ ],+ )+ def test_credentials_are_read_from_the_selected_auth_method(+ self, selection: str, expected: QualtricsCredentials+ ) -> None:+ assert source_module._credentials_from_config(_config(selection)) == expected++ def test_validate_credentials_plumbs_config_through(self) -> None:+ with mock.patch.object(source_module, "validate_qualtrics_credentials", return_value=(True, None)) as validate:+ assert self.source.validate_credentials(_config(), team_id=7, schema_name="users") == (True, None)++ assert validate.call_args.kwargs == {+ "datacenter_id": "iad1",+ "credentials": QualtricsCredentials(method="api_token", api_token="tok-123"),+ "api_version": "v3",+ "schema_name": "users",+ "team_id": 7,+ }++ def test_resumable_manager_is_bound_to_the_resume_dataclass(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is QualtricsResumeConfig++ def test_source_for_pipeline_passes_the_incremental_watermark(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs())+ inputs = _inputs(+ schema_name="survey_responses",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ with mock.patch.object(source_module, "qualtrics_source") as build:+ self.source.source_for_pipeline(_config(), manager, inputs)++ kwargs = build.call_args.kwargs+ assert kwargs["endpoint"] == "survey_responses"+ assert kwargs["api_version"] == "v3"+ assert kwargs["team_id"] == 1+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_drops_the_watermark_on_a_full_refresh(self) -> None:+ manager = self.source.get_resumable_source_manager(_inputs())+ inputs = _inputs(+ schema_name="surveys",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ )++ with mock.patch.object(source_module, "qualtrics_source") as build:+ self.source.source_for_pipeline(_config(), manager, inputs)++ assert build.call_args.kwargs["db_incremental_field_last_value"] is None