Skip to content

: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.

feat(data-warehouse): add 4 missing tables to the Qualtrics source (#124874)

Tom Owers5575c521f58a
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 0e3017f1e00e..48ab07a5e8a6 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1312,7 +1312,6 @@
2 products/warehouse_sources/backend/temporal/data_imports/sources/mailchimp/settings.py
2 products/warehouse_sources/backend/temporal/data_imports/sources/meta_ads/meta_ads.py
2 products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
-2 products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py
2 products/warehouse_sources/backend/temporal/data_imports/sources/reddit_ads/reddit_ads.py
2 products/warehouse_sources/backend/temporal/data_imports/sources/servicenow/servicenow.py
2 products/warehouse_sources/backend/temporal/data_imports/sources/temporalio/temporalio.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 20a29a5a1363..4b230b3e7bf0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -9937,10 +9937,10 @@ Today (7): `distributions`, `divisions`, `groups`, `survey_questions`, `survey_r
Diffed against: <https://stoplight.io/api/v1/projects/cHJqOjk3NDQ/table-of-contents>
-- [ ] `Directory contacts (GET /API/v3/directories/{directoryId}/contacts)` — analyze respondent identities, external references, and opt-out status across surveys (high)
-- [ ] `Mailing lists (GET /API/v3/directories/{directoryId}/mailinglists)` — identify distribution audiences and compare results by mailing list (high)
-- [ ] `Directories (GET /API/v3/directories)` — identify contact directories and discover parents for audience tables (high)
-- [ ] `Distribution history (GET /API/v3/distributions/{distributionId}/history)` — measure recipient delivery and participation for existing survey distributions (high)
+- [x] `Directory contacts (GET /API/v3/directories/{directoryId}/contacts)` — analyze respondent identities, external references, and opt-out status across surveys (high)
+- [x] `Mailing lists (GET /API/v3/directories/{directoryId}/mailinglists)` — identify distribution audiences and compare results by mailing list (high)
+- [x] `Directories (GET /API/v3/directories)` — identify contact directories and discover parents for audience tables (high)
+- [x] `Distribution history (GET /API/v3/distributions/{distributionId}/history)` — measure recipient delivery and participation for existing survey distributions (high)
- [ ] `Mailing list contacts (GET /API/v3/directories/{directoryId}/mailinglists/{mailingListId}/contacts)` — analyze audience membership and compare response rates across recipient segments (medium)
- [ ] `Group members (GET /API/v3/groups/{groupId}/members)` — connect existing groups and users to analyze organizational membership (medium)
- [ ] `Contact transactions (GET /API/v3/directories/{directoryId}/contacts/{contactId}/transactions)` — connect customer interactions with survey feedback (medium)
diff --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.py
index 5490670ce0bd..6432933d227c 100644
--- 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.py
@@ -106,4 +106,63 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"creatorId": "Identifier of the Qualtrics user who created the division.",
},
},
+ "directories": {
+ "description": "XM Directory directories (also called pools) in the Qualtrics brand.",
+ "docs_url": "https://api.qualtrics.com/013df5106e3c7-list-directories-for-a-brand",
+ "columns": {
+ "directoryId": "Unique directory identifier, prefixed with `POOL_`.",
+ "name": "Name of the directory.",
+ "contactCount": "Approximate number of contacts in the directory.",
+ "isDefault": "Whether this is the default directory of the brand.",
+ "deduplicationCriteria": "Contact fields the directory uses to detect duplicate contacts.",
+ },
+ },
+ "directory_contacts": {
+ "description": "Contacts stored in each XM Directory directory, with their opt-out status.",
+ "docs_url": "https://api.qualtrics.com/d326cdc7e69ae-list-directory-contacts",
+ "columns": {
+ "contactId": "Unique contact identifier, prefixed with `CID_`.",
+ "directoryId": "Identifier of the directory the contact belongs to.",
+ "firstName": "First name of the contact.",
+ "lastName": "Last name of the contact.",
+ "email": "Email address of the contact.",
+ "phone": "Phone number of the contact.",
+ "extRef": "External reference set for the contact, often an ID from another system.",
+ "language": "Preferred language code of the contact.",
+ "directoryUnsubscribed": "Whether the contact opted out of the whole directory.",
+ "directoryUnsubscribeDate": "Timestamp the contact opted out of the directory.",
+ },
+ },
+ "mailing_lists": {
+ "description": "Mailing lists in each XM Directory directory, used as distribution audiences.",
+ "docs_url": "https://api.qualtrics.com/dd83f1535056c-list-mailing-lists",
+ "columns": {
+ "mailingListId": "Unique mailing list identifier, prefixed with `CG_`.",
+ "directoryId": "Identifier of the directory the mailing list belongs to.",
+ "name": "Name of the mailing list.",
+ "ownerId": "Identifier of the user or group that owns the mailing list.",
+ "contactCount": "Approximate number of contacts in the mailing list.",
+ "creationDate": "Time the mailing list was created, in Unix milliseconds.",
+ "lastModifiedDate": "Time the mailing list was last changed, in Unix milliseconds.",
+ },
+ },
+ "distribution_history": {
+ "description": "Per-contact delivery and response history for each survey distribution.",
+ "docs_url": "https://api.qualtrics.com/8840efb2c71a8-list-distribution-history",
+ "columns": {
+ "distributionId": "Identifier of the distribution that was sent.",
+ "contactId": "Identifier of the contact the entry belongs to.",
+ "surveyId": "Identifier of the survey the distribution was sent for.",
+ "contactLookupId": "Identifier of the contact's membership in the mailing list.",
+ "status": "Delivery status for the contact, for example `Success`, `Opened` or `Skipped`.",
+ "surveyLink": "Survey link sent to the contact, if any.",
+ "contactFrequencyRuleId": "Contact frequency rule that skipped this contact, if the status is `Skipped`.",
+ "responseId": "Identifier of the response the contact submitted, if any.",
+ "sentAt": "Timestamp the distribution was sent to the contact.",
+ "openedAt": "Timestamp the contact opened the survey.",
+ "responseStartedAt": "Timestamp the contact started a response.",
+ "responseCompletedAt": "Timestamp the contact completed a response.",
+ "surveySessionId": "Identifier of the contact's survey session.",
+ },
+ },
}
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.py
index e51ffcd9d06c..1fbac25d0a3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/qualtrics.py
@@ -66,11 +66,11 @@ EXPORT_BATCH_SIZE = 1000
# 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
+# The fan-out parent-id list (surveys or directories) 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_PARENT_ID_LENGTH = 64
+MAX_PARENT_COUNT = 200_000
# OAuth2 client-credentials tokens last ~1h; re-mint before the deadline so no request rides
# a token that expires mid-flight.
@@ -82,7 +82,7 @@ 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_\-]+$")
+_PARENT_ID_PATTERN = re.compile(r"^[A-Za-z0-9_\-]+$")
class QualtricsRetryableError(Exception):
@@ -113,13 +113,19 @@ class QualtricsExportFailedError(Exception):
pass
[email protected](frozen=True)
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.
+ # Number of parents (surveys or directories) already walked to completion (fan-out
+ # endpoints). Restarting the in-flight parent is intentional — merge dedupes its rows on the
+ # primary key.
parent_index: int = 0
+ # Page checkpoint inside the in-flight parent: a resumed full refresh appends without
+ # deduping, so replaying the parent would duplicate rows.
+ parent_id: str | None = None
+ child_id: str | None = None
+ child_next_page: str | None = None
@frozen
@@ -406,13 +412,13 @@ def _next_page(payload: Any) -> str | None:
return next_page if isinstance(next_page, str) and next_page else None
-def _iter_collection(
+def _iter_pages(
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."""
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Walk a `result.elements` collection, yielding each page with its `result.nextPage` URL."""
url = start_url or first_url
pages = 0
@@ -426,42 +432,73 @@ def _iter_collection(
)
payload = client.get_json(url)
- elements = _elements(payload)
- if elements:
- yield elements
-
next_url = _next_page(payload)
+ yield _elements(payload), next_url
if not next_url:
break
+ url = next_url
+ pages += 1
+
+
+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."""
+ for elements, next_url in _iter_pages(client, first_url, resumable_source_manager, start_url):
+ if elements:
+ yield elements
# Saved AFTER yielding so a crash re-yields the last page rather than skipping it.
- if resumable_source_manager is not None:
+ if next_url and 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.
+def _iter_child_pages(
+ client: QualtricsClient,
+ first_url: str,
+ resumable_source_manager: ResumableSourceManager[QualtricsResumeConfig],
+ checkpoint: QualtricsResumeConfig,
+ start_url: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk one child collection of a fan-out parent, staging the page cursor before each yield."""
+ for elements, next_url in _iter_pages(client, first_url, resumable_source_manager, start_url):
+ resumable_source_manager.save_state(dataclasses.replace(checkpoint, child_next_page=next_url))
+ if elements:
+ yield elements
+ else:
+ resumable_source_manager.safe_point()
+
+
+def _path_safe_id(raw: Any) -> str | None:
+ """Ids go straight into request paths, so anything that isn't a plain Qualtrics id is dropped."""
+ if not raw:
+ return None
+ value = str(raw)
+ if len(value) > MAX_PARENT_ID_LENGTH or not _PARENT_ID_PATTERN.match(value):
+ return None
+ return value
- 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.
+
+def _parent_ids(client: QualtricsClient, path: str, id_field: str, params: dict[str, Any] | None = None) -> list[str]:
+ """Collect the parent ids (`SV_...` surveys or `POOL_...` directories) a fan-out iterates.
+
+ The list is fully materialized — resuming the fan-out addresses parents 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 page in _iter_collection(client, client.url(path, params), 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):
+ parent_id = _path_safe_id(element.get(id_field))
+ if parent_id is None:
continue
- ids.append(survey_id)
- if len(ids) > MAX_SURVEY_COUNT:
+ ids.append(parent_id)
+ if len(ids) > MAX_PARENT_COUNT:
raise QualtricsResponseTooLargeError(
- f"Qualtrics returned more than {MAX_SURVEY_COUNT} surveys; refusing to buffer them all"
+ f"Qualtrics returned more than {MAX_PARENT_COUNT} parents from {path}; refusing to buffer them all"
)
return ids
@@ -718,19 +755,22 @@ def get_rows(
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:
+ if not config.fans_out:
yield from _iter_collection(
client,
- client.url(config.path),
+ client.url(config.path, config.params),
resumable_source_manager,
start_url=resume.next_page if resume else None,
)
return
- survey_ids = _survey_ids(client)
+ if config.fetch_mode == "directory_path":
+ parent_ids = _parent_ids(client, "/directories", "directoryId")
+ else:
+ parent_ids = _parent_ids(client, "/surveys", "id")
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)}")
+ logger.debug(f"Qualtrics: resuming {endpoint} from parent {start_index} of {len(parent_ids)}")
start_date = (
format_incremental_value(db_incremental_field_last_value)
@@ -738,21 +778,44 @@ def get_rows(
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
+ for index in range(start_index, len(parent_ids)):
+ # Every earlier parent's rows are already yielded, so the run can hand off here. Many
+ # parents (empty directories, surveys with no distributions) yield no rows at all.
+ resumable_source_manager.safe_point()
+ parent_id = parent_ids[index]
+ # Only the in-flight parent resumes mid-way, and only if the parent list hasn't shifted.
+ child_resume = resume if resume and index == start_index and resume.parent_id == parent_id else None
+ yield from _rows_for_parent(
+ client, config, index, parent_id, start_date, logger, resumable_source_manager, child_resume
+ )
+ # Saved AFTER the parent's rows are yielded, so a crash replays that parent 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(
+def _rows_for_parent(
client: QualtricsClient,
config: QualtricsEndpointConfig,
- survey_id: str,
+ parent_index: int,
+ parent_id: str,
start_date: str | None,
logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[QualtricsResumeConfig],
+ child_resume: QualtricsResumeConfig | None,
) -> Iterator[list[dict[str, Any]]]:
+ if config.fetch_mode == "directory_path":
+ url = client.url(config.path.format(directory_id=parent_id), config.params)
+ checkpoint = QualtricsResumeConfig(parent_index=parent_index, parent_id=parent_id)
+ start_url = child_resume.child_next_page if child_resume else None
+ for page in _iter_child_pages(client, url, resumable_source_manager, checkpoint, start_url):
+ yield [{**row, "directoryId": parent_id} for row in page]
+ return
+
+ if config.fetch_mode == "distribution_path":
+ yield from _distribution_rows(client, config, parent_index, parent_id, resumable_source_manager, child_resume)
+ return
+
+ survey_id = parent_id
if config.fetch_mode == "survey_export":
yield from _export_responses(client, survey_id, start_date, logger)
return
@@ -769,6 +832,33 @@ def _rows_for_survey(
yield [{**row, "surveyId": survey_id} for row in elements]
+def _distribution_rows(
+ client: QualtricsClient,
+ config: QualtricsEndpointConfig,
+ parent_index: int,
+ survey_id: str,
+ resumable_source_manager: ResumableSourceManager[QualtricsResumeConfig],
+ child_resume: QualtricsResumeConfig | None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk each distribution of one survey, then that distribution's paginated rows."""
+ distribution_ids = _parent_ids(client, "/distributions", "id", {"surveyId": survey_id})
+ start, start_url = 0, None
+ if child_resume and child_resume.child_id in distribution_ids:
+ start = distribution_ids.index(child_resume.child_id)
+ start_url = child_resume.child_next_page
+ if start_url is None:
+ start += 1
+
+ for position in range(start, len(distribution_ids)):
+ resumable_source_manager.safe_point()
+ distribution_id = distribution_ids[position]
+ url = client.url(config.path.format(distribution_id=distribution_id), config.params)
+ checkpoint = QualtricsResumeConfig(parent_index=parent_index, parent_id=survey_id, child_id=distribution_id)
+ page_start = start_url if position == start else None
+ for page in _iter_child_pages(client, url, resumable_source_manager, checkpoint, page_start):
+ yield [{**row, "surveyId": survey_id, "distributionId": distribution_id} for row in page]
+
+
def validate_credentials(
datacenter_id: str,
credentials: QualtricsCredentials,
@@ -852,8 +942,8 @@ def qualtrics_source(
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 —
+ # Fan-out endpoints arrive grouped by parent, 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",
+ sort_mode="desc" if config.fans_out 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.py
index f566a3382320..93a3d089c664 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/qualtrics/settings.py
@@ -14,25 +14,34 @@ QUALTRICS_DEFAULT_DOMAIN_SUFFIX = ".qualtrics.com"
# "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"]
+# "directory_path" — a paginated `result.elements` collection per XM Directory, keyed in the path
+# "distribution_path" — a paginated collection per distribution, reached through each survey's
+# distribution list (surveys -> distributions -> rows)
+FetchMode = Literal["list", "survey_query", "survey_path", "survey_export", "directory_path", "distribution_path"]
@dataclass(frozen=True)
class QualtricsEndpointConfig:
name: str
- # Path under `/API/{version}`. `{survey_id}` is substituted per parent survey.
+ # Path under `/API/{version}`. `{survey_id}`, `{directory_id}` or `{distribution_id}` is
+ # substituted per parent.
path: str
primary_key: list[str]
fetch_mode: FetchMode = "list"
+ params: dict[str, str] = field(default_factory=dict)
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:
+ def fans_out(self) -> bool:
return self.fetch_mode != "list"
+ @property
+ def parent_path(self) -> str:
+ return "/directories" if self.fetch_mode == "directory_path" else "/surveys"
+
RECORDED_DATE_INCREMENTAL = incremental_field("recordedDate")
@@ -82,6 +91,32 @@ QUALTRICS_ENDPOINTS: dict[str, QualtricsEndpointConfig] = {
incremental_fields=[RECORDED_DATE_INCREMENTAL],
partition_key="recordedDate",
),
+ # The XM Directory endpoints below have no modified-since filter, so they are full refresh.
+ "directories": QualtricsEndpointConfig(
+ name="directories",
+ path="/directories",
+ primary_key=["directoryId"],
+ params={"includeCount": "true"},
+ ),
+ "directory_contacts": QualtricsEndpointConfig(
+ name="directory_contacts",
+ path="/directories/{directory_id}/contacts",
+ primary_key=["directoryId", "contactId"],
+ fetch_mode="directory_path",
+ ),
+ "mailing_lists": QualtricsEndpointConfig(
+ name="mailing_lists",
+ path="/directories/{directory_id}/mailinglists",
+ primary_key=["directoryId", "mailingListId"],
+ fetch_mode="directory_path",
+ params={"includeCount": "true"},
+ ),
+ "distribution_history": QualtricsEndpointConfig(
+ name="distribution_history",
+ path="/distributions/{distribution_id}/history",
+ primary_key=["distributionId", "contactId"],
+ fetch_mode="distribution_path",
+ ),
}
ENDPOINTS = tuple(QUALTRICS_ENDPOINTS)
@@ -91,7 +126,7 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
}
# 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.
+# URL without a parent id, so they validate through their parent 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()
+ name: config.parent_path if config.fans_out 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.py
index 9c4db637c74b..dd33cec0a12e 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
@@ -89,7 +89,7 @@ class QualtricsSource(ResumableSource[QualtricsSourceConfig, QualtricsResumeConf
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.
+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. The directories, directory contacts, mailing lists and distribution history tables need XM Directory.
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.
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.py
index 3b85ca64f496..6a09ab0f7622 100644
--- 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.py
@@ -213,26 +213,159 @@ class TestCollectionPagination:
assert isinstance(result.raised, QualtricsPaginationLimitError)
+ @pytest.mark.parametrize(
+ "endpoint, script, expected",
+ [
+ ("directories", [_json(_collection([{"directoryId": "POOL_1"}]))], ["true"]),
+ (
+ "mailing_lists",
+ [_json(_collection([{"directoryId": "POOL_1"}])), _json(_collection([{"mailingListId": "CG_1"}]))],
+ [None, "true"],
+ ),
+ ("users", [_json(_collection([{"id": "UR_1"}]))], [None]),
+ ],
+ )
+ def test_contact_counts_are_requested_only_where_declared(
+ self, endpoint: str, script: list[ScriptedResponse], expected: list[str | None]
+ ) -> None:
+ result = _drive(endpoint, script)
+
+ assert result.raised is None
+ assert result.params("includeCount") == expected
+
class TestSurveyFanout:
- def test_query_fanout_stamps_the_parent_survey_id(self) -> None:
- result = _drive(
- "distributions",
- [
- _json(_collection([{"id": "SV_1"}, {"id": "SV_2"}])),
- _json(_collection([{"id": "EMD_1"}])),
- _json(_collection([{"id": "EMD_2"}])),
- ],
- )
+ @pytest.mark.parametrize(
+ "endpoint, script, expected_items, expected_paths, expected_child_states",
+ [
+ (
+ "distributions",
+ [
+ _json(_collection([{"id": "SV_1"}, {"id": "SV_2"}])),
+ _json(_collection([{"id": "EMD_1"}])),
+ _json(_collection([{"id": "EMD_2"}])),
+ ],
+ [[{"id": "EMD_1", "surveyId": "SV_1"}], [{"id": "EMD_2", "surveyId": "SV_2"}]],
+ ["/API/v3/surveys", "/API/v3/distributions", "/API/v3/distributions"],
+ [[], []],
+ ),
+ (
+ "directory_contacts",
+ [
+ _json(_collection([{"directoryId": "POOL_1"}, {"directoryId": "POOL_2"}])),
+ _json(
+ _collection(
+ [{"contactId": "CID_1"}], next_page=f"{BASE}/directories/POOL_1/contacts?skipToken=a"
+ )
+ ),
+ _json(_collection([{"contactId": "CID_2"}])),
+ _json(_collection([{"contactId": "CID_3"}])),
+ ],
+ [
+ [{"contactId": "CID_1", "directoryId": "POOL_1"}],
+ [{"contactId": "CID_2", "directoryId": "POOL_1"}],
+ [{"contactId": "CID_3", "directoryId": "POOL_2"}],
+ ],
+ [
+ "/API/v3/directories",
+ "/API/v3/directories/POOL_1/contacts",
+ "/API/v3/directories/POOL_1/contacts",
+ "/API/v3/directories/POOL_2/contacts",
+ ],
+ [
+ [
+ QualtricsResumeConfig(
+ parent_id="POOL_1", child_next_page=f"{BASE}/directories/POOL_1/contacts?skipToken=a"
+ ),
+ QualtricsResumeConfig(parent_id="POOL_1"),
+ ],
+ [QualtricsResumeConfig(parent_index=1, parent_id="POOL_2")],
+ ],
+ ),
+ (
+ "mailing_lists",
+ [
+ _json(_collection([{"directoryId": "POOL_1"}, {"directoryId": "POOL_2"}])),
+ _json(_collection([{"mailingListId": "CG_1"}])),
+ _json(_collection([{"mailingListId": "CG_2"}])),
+ ],
+ [
+ [{"mailingListId": "CG_1", "directoryId": "POOL_1"}],
+ [{"mailingListId": "CG_2", "directoryId": "POOL_2"}],
+ ],
+ [
+ "/API/v3/directories",
+ "/API/v3/directories/POOL_1/mailinglists",
+ "/API/v3/directories/POOL_2/mailinglists",
+ ],
+ [
+ [QualtricsResumeConfig(parent_id="POOL_1")],
+ [QualtricsResumeConfig(parent_index=1, parent_id="POOL_2")],
+ ],
+ ),
+ (
+ "distribution_history",
+ [
+ _json(_collection([{"id": "SV_1"}, {"id": "SV_2"}])),
+ _json(_collection([{"id": "EMD_1"}, {"id": "EMD/../x"}, {"id": "EMD_2"}])),
+ _json(
+ _collection(
+ [{"contactId": "CID_1"}], next_page=f"{BASE}/distributions/EMD_1/history?skipToken=a"
+ )
+ ),
+ _json(_collection([{"contactId": "CID_2"}])),
+ _json(_collection([])),
+ _json(_collection([])),
+ ],
+ [
+ [{"contactId": "CID_1", "surveyId": "SV_1", "distributionId": "EMD_1"}],
+ [{"contactId": "CID_2", "surveyId": "SV_1", "distributionId": "EMD_1"}],
+ ],
+ [
+ "/API/v3/surveys",
+ "/API/v3/distributions",
+ "/API/v3/distributions/EMD_1/history",
+ "/API/v3/distributions/EMD_1/history",
+ "/API/v3/distributions/EMD_2/history",
+ "/API/v3/distributions",
+ ],
+ [
+ [
+ QualtricsResumeConfig(
+ parent_id="SV_1",
+ child_id="EMD_1",
+ child_next_page=f"{BASE}/distributions/EMD_1/history?skipToken=a",
+ ),
+ QualtricsResumeConfig(parent_id="SV_1", child_id="EMD_1"),
+ QualtricsResumeConfig(parent_id="SV_1", child_id="EMD_2"),
+ ],
+ [],
+ ],
+ ),
+ ],
+ )
+ def test_fanout_stamps_the_parent_id(
+ self,
+ endpoint: str,
+ script: list[ScriptedResponse],
+ expected_items: list[list[dict[str, Any]]],
+ expected_paths: list[str],
+ expected_child_states: list[list[QualtricsResumeConfig]],
+ ) -> None:
+ result = _drive(endpoint, script)
- assert result.items == [
- [{"id": "EMD_1", "surveyId": "SV_1"}],
- [{"id": "EMD_2", "surveyId": "SV_2"}],
+ assert result.raised is None
+ assert result.items == expected_items
+ assert result.paths == expected_paths
+ assert result.saved_states == [
+ *expected_child_states[0],
+ QualtricsResumeConfig(parent_index=1),
+ *expected_child_states[1],
+ QualtricsResumeConfig(parent_index=2),
]
- assert result.saved_states == [QualtricsResumeConfig(parent_index=1), QualtricsResumeConfig(parent_index=2)]
def test_over_length_survey_ids_are_dropped(self) -> None:
- with mock.patch.object(qualtrics_module, "MAX_SURVEY_ID_LENGTH", 5):
+ with mock.patch.object(qualtrics_module, "MAX_PARENT_ID_LENGTH", 5):
result = _drive(
"survey_questions",
[
@@ -244,7 +377,7 @@ class TestSurveyFanout:
assert result.items == [[{"QuestionID": "QID1", "surveyId": "SV_ok"}]]
def test_too_many_surveys_is_refused(self) -> None:
- with mock.patch.object(qualtrics_module, "MAX_SURVEY_COUNT", 1):
+ with mock.patch.object(qualtrics_module, "MAX_PARENT_COUNT", 1):
result = _drive("survey_questions", [_json(_collection([{"id": "SV_1"}, {"id": "SV_2"}]))])
assert isinstance(result.raised, QualtricsResponseTooLargeError)
@@ -263,6 +396,91 @@ class TestSurveyFanout:
assert result.paths[1] == "/API/v3/survey-definitions/SV_3/questions"
assert result.saved_states == [QualtricsResumeConfig(parent_index=3)]
+ @pytest.mark.parametrize(
+ "endpoint, resume_state, script, expected_items, expected_paths",
+ [
+ (
+ "directory_contacts",
+ QualtricsResumeConfig(
+ parent_index=1,
+ parent_id="POOL_2",
+ child_next_page=f"{BASE}/directories/POOL_2/contacts?skipToken=b",
+ ),
+ [
+ _json(_collection([{"directoryId": "POOL_1"}, {"directoryId": "POOL_2"}])),
+ _json(_collection([{"contactId": "CID_9"}])),
+ ],
+ [[{"contactId": "CID_9", "directoryId": "POOL_2"}]],
+ ["/API/v3/directories", "/API/v3/directories/POOL_2/contacts"],
+ ),
+ (
+ "directory_contacts",
+ QualtricsResumeConfig(
+ parent_index=1,
+ parent_id="POOL_9",
+ child_next_page=f"{BASE}/directories/POOL_9/contacts?skipToken=b",
+ ),
+ [
+ _json(_collection([{"directoryId": "POOL_1"}, {"directoryId": "POOL_2"}])),
+ _json(_collection([{"contactId": "CID_1"}])),
+ ],
+ [[{"contactId": "CID_1", "directoryId": "POOL_2"}]],
+ ["/API/v3/directories", "/API/v3/directories/POOL_2/contacts"],
+ ),
+ (
+ "distribution_history",
+ QualtricsResumeConfig(
+ parent_index=0,
+ parent_id="SV_1",
+ child_id="EMD_2",
+ child_next_page=f"{BASE}/distributions/EMD_2/history?skipToken=b",
+ ),
+ [
+ _json(_collection([{"id": "SV_1"}])),
+ _json(_collection([{"id": "EMD_1"}, {"id": "EMD_2"}, {"id": "EMD_3"}])),
+ _json(_collection([{"contactId": "CID_5"}])),
+ _json(_collection([{"contactId": "CID_6"}])),
+ ],
+ [
+ [{"contactId": "CID_5", "surveyId": "SV_1", "distributionId": "EMD_2"}],
+ [{"contactId": "CID_6", "surveyId": "SV_1", "distributionId": "EMD_3"}],
+ ],
+ [
+ "/API/v3/surveys",
+ "/API/v3/distributions",
+ "/API/v3/distributions/EMD_2/history",
+ "/API/v3/distributions/EMD_3/history",
+ ],
+ ),
+ (
+ "distribution_history",
+ QualtricsResumeConfig(parent_index=0, parent_id="SV_1", child_id="EMD_1"),
+ [
+ _json(_collection([{"id": "SV_1"}])),
+ _json(_collection([{"id": "EMD_1"}, {"id": "EMD_2"}])),
+ _json(_collection([{"contactId": "CID_7"}])),
+ ],
+ [[{"contactId": "CID_7", "surveyId": "SV_1", "distributionId": "EMD_2"}]],
+ ["/API/v3/surveys", "/API/v3/distributions", "/API/v3/distributions/EMD_2/history"],
+ ),
+ ],
+ )
+ def test_full_refresh_fanout_resumes_after_the_last_written_page(
+ self,
+ endpoint: str,
+ resume_state: QualtricsResumeConfig,
+ script: list[ScriptedResponse],
+ expected_items: list[list[dict[str, Any]]],
+ expected_paths: list[str],
+ ) -> None:
+ result = _drive(endpoint, script, resume_state=resume_state)
+
+ assert result.raised is None
+ assert result.items == expected_items
+ assert result.paths == expected_paths
+ expected_token = "b" if resume_state.child_next_page and resume_state.parent_id != "POOL_9" else None
+ assert result.params("skipToken")[len(expected_paths) - len(expected_items)] == expected_token
+
class TestResponseExport:
NDJSON = "\n".join(