: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 sequenzy import source (#107253)
Tom Owers3575d211fdc0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e7843e5751d3..b8c2e7222d62 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -624,6 +624,7 @@ the row lists both.| sendowl | HTTP | requests | ✅ || sentinelone | HTTP | requests | ✅ || sentry | HTTP | requests + `rest_source.RESTClient` | ✅ |+| sequenzy | HTTP | requests + `rest_source.RESTClient` | ✅ || servicem8 | HTTP | requests + `rest_source.RESTClient` | ✅ || servicenow | HTTP | requests | ✅ || sftp | SSH (SFTP) | paramiko | ➖ |@@ -1356,7 +1357,6 @@ doesn't conflict with concurrent PRs.- semrush- sendpulse- senseforce-- sequenzy- serpstat- service_fusion- servicetitandiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sequenzy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sequenzy.pyindex 0acf3f26c0cd..e3c39f2e5dd2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sequenzy.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sequenzy.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SequenzySourceConfig(config.Config):- pass+ api_key: str+ company_id: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/canonical_descriptions.pynew file mode 100644index 000000000000..7f43a233d033--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/canonical_descriptions.py@@ -0,0 +1,124 @@+"""Canonical, documentation-sourced descriptions for Sequenzy endpoints and columns.++Sourced from the official Sequenzy API reference (https://docs.sequenzy.com/api-reference).+Keyed by the endpoint names in `settings.py` `ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Sequenzy table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "subscribers": {+ "description": "An email contact in the workspace, with status, tags, and custom attributes.",+ "docs_url": "https://docs.sequenzy.com/api-reference/subscribers/list",+ "columns": {+ "id": "Unique identifier for the subscriber.",+ "email": "The subscriber's email address.",+ "firstName": "The subscriber's first name.",+ "lastName": "The subscriber's last name.",+ "status": "Delivery status: active, unsubscribed, or bounced.",+ "unsubscribedAt": "When the contact opted out. Null unless the contact is currently unsubscribed, and null for contacts imported as already unsubscribed.",+ "emailProvider": "Detected mailbox provider of the address (e.g. gmail).",+ "tags": "Names of the tags applied to the subscriber.",+ "customAttributes": "Custom attribute key-value pairs stored on the subscriber.",+ "createdAt": "When the subscriber was created.",+ "updatedAt": "When the subscriber was last updated. Moves on any tag or attribute write.",+ },+ },+ "tags": {+ "description": "A tag definition used to segment subscribers and trigger automations.",+ "docs_url": "https://docs.sequenzy.com/api-reference/tags/list",+ "columns": {+ "id": "Unique identifier for the tag.",+ "name": "The tag's name.",+ "color": "Display color of the tag in the Sequenzy dashboard.",+ "isSystem": "Whether the tag is a built-in system tag rather than a user-created one.",+ },+ },+ "lists": {+ "description": "A subscriber list, with current membership counts.",+ "docs_url": "https://docs.sequenzy.com/api-reference/lists/list",+ "columns": {+ "id": "Unique identifier for the list.",+ "name": "The list's name.",+ "description": "Description of the list.",+ "isPrivate": "Whether the list is hidden from subscribers' preference pages.",+ "allowMemberUnsubscribe": "Whether current members of a private list can see it and opt out through preferences.",+ "createdAt": "When the list was created.",+ "subscriberCount": "Current members of any status. Members who unsubscribed from the list are not counted.",+ "activeSubscriberCount": "Current members with status active.",+ },+ },+ "segments": {+ "description": "A saved segment: a set of filters over subscribers, with live match counts.",+ "docs_url": "https://docs.sequenzy.com/api-reference/segments/list",+ "columns": {+ "id": "Unique identifier for the segment.",+ "name": "The segment's name.",+ "filters": "The segment's saved filter conditions.",+ "filterJoinOperator": "How the top-level filters combine: and / or.",+ "format": "Version of the stored filter format.",+ "createdAt": "When the segment was created.",+ "subscriberCount": "Matching contacts of every status, recalculated from the saved filters on each request.",+ "activeSubscriberCount": "Matching contacts with status active.",+ },+ },+ "campaigns": {+ "description": "An email campaign (broadcast), with scheduling, delivery pacing, and audience state.",+ "docs_url": "https://docs.sequenzy.com/api-reference/campaigns/list",+ "columns": {+ "id": "Unique identifier for the campaign.",+ "name": "The campaign's name.",+ "subject": "Subject line of the campaign email.",+ "emailId": "ID of the email content linked to the campaign.",+ "emailPreset": "The linked email's format: branded, minimal, or null for SMS campaigns and raw-HTML emails.",+ "status": "Campaign status: draft, scheduled, sent, sending, cancelled, paused, waiting_approval, or rejected.",+ "hasAudience": "Whether an explicit audience is configured. Does not count eligible recipients or validate that referenced audiences still exist.",+ "labels": "Dashboard label names assigned to the campaign.",+ "scheduledAt": "When the campaign is scheduled to send.",+ "sentAt": "When the campaign finished sending.",+ "spreadOverHours": "Hours the send is spread over, for paced delivery.",+ "sendTimeOptimization": "Whether per-recipient send-time optimization is enabled.",+ "sendTimeWindowHours": "Size of the send-time optimization window in hours.",+ "sendInRecipientTimezone": "Whether the scheduled time is interpreted in each recipient's timezone.",+ "scheduledTimezone": "Timezone the scheduled time was set in.",+ "maxRecipients": "Recipient cap for the send. Null when the whole audience is targeted.",+ "createdAt": "When the campaign was created.",+ },+ },+ "sequences": {+ "description": "An automation sequence (email workflow), with trigger, run state, and sending window.",+ "docs_url": "https://docs.sequenzy.com/api-reference/sequences/list",+ "columns": {+ "id": "Unique identifier for the sequence.",+ "name": "The sequence's name.",+ "status": "Stored status: draft, active, paused, or archived. An active sequence may still have enrollments paused.",+ "enrollmentPaused": "Whether new enrollments are paused while existing recipients continue.",+ "effectiveStatus": "Combined run state: draft, live, enrollment_paused, paused, or archived. Prefer this over status.",+ "acceptsNewEnrollments": "Whether new subscribers can enter the sequence.",+ "processesExistingEnrollments": "Whether recipients already in the sequence continue to advance.",+ "trigger": "What enrolls subscribers into the sequence.",+ "sendingWindow": "Days and hours the sequence is allowed to send in, with timezone.",+ "createdAt": "When the sequence was created.",+ },+ },+ "email_metrics": {+ "description": "Per-email engagement metrics: one row per campaign and per sequence email step, with delivery funnel, conversions, and revenue.",+ "docs_url": "https://docs.sequenzy.com/api-reference/analytics/email-metrics",+ "columns": {+ "emailType": "Whether the row is a campaign or a sequence email step.",+ "emailId": "Campaign ID for campaigns, automation node ID for sequence emails.",+ "name": "Campaign name, or the step's subject line falling back to its node label.",+ "campaignId": "Campaign ID, or null for sequence emails.",+ "sequenceId": "Sequence ID, or null for campaigns.",+ "sequenceName": "Name of the sequence the step belongs to.",+ "automationNodeId": "Node ID of the sequence step.",+ "step": "1-based position of the email in its sequence, or null for campaigns.",+ "stats": "Delivery funnel for this email alone: sends, deliveries, bounces, opens, clicks, unsubscribes and rates.",+ "conversions": "Goal conversions attributed to this email (last-touch).",+ "revenueCents": "Attributed revenue in cents from purchase events.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/sequenzy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/sequenzy.pynew file mode 100644index 000000000000..6716d20d441f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/sequenzy.py@@ -0,0 +1,187 @@+import dataclasses+from typing import Any, Optional++from posthog.dataclasses import frozen++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponseCursorPaginator,+ OffsetPaginator,+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+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.sequenzy.settings import (+ ENDPOINTS_CONFIG,+ SEQUENZY_BASE_URL,+ SequenzyEndpointConfig,+)+++@frozen+class SequenzyResumeConfig:+ """Snapshot of the framework paginator's resume state.++ Exactly one field is set, matching the endpoint's pagination style: `cursor` for+ subscribers, `offset` for campaigns/sequences, `page` for email metrics. The field+ names mirror the keys of the framework paginators' `get_resume_state` dicts so the+ two shapes convert without a mapping table.+ """++ cursor: str | None = None+ offset: int | None = None+ page: int | None = None+++def _paginator_state(resume: SequenzyResumeConfig) -> Optional[dict[str, Any]]:+ state = {key: value for key, value in dataclasses.asdict(resume).items() if value is not None}+ return state or None+++def _make_paginator(config: SequenzyEndpointConfig) -> BasePaginator:+ if config.pagination == "cursor":+ return JSONResponseCursorPaginator(cursor_path="pagination.nextCursor", cursor_param="cursor")+ if config.pagination == "offset":+ assert config.page_size is not None+ return OffsetPaginator(+ limit=config.page_size,+ offset_param="offset",+ limit_param="limit",+ total_path="pagination.total",+ )+ if config.pagination == "page":+ return PageNumberPaginator(base_page=1, page_param="page", total_path="pagination.totalPages")+ return SinglePagePaginator()+++def get_resource(name: str) -> EndpointResource:+ config = ENDPOINTS_CONFIG[name]++ params: dict[str, Any] = dict(config.params)+ # The cursor and page-number paginators only inject their own pagination param, so+ # the page size rides along as a plain query param. The offset paginator sends+ # `limit` itself.+ if config.pagination in ("cursor", "page") and config.page_size is not None:+ params["limit"] = config.page_size++ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": {+ "path": config.path,+ "data_selector": config.data_selector,+ "params": params,+ "paginator": _make_paginator(config),+ },+ "table_format": "delta",+ }+++def sequenzy_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[SequenzyResumeConfig],+ company_id: str | None = None,+) -> SourceResponse:+ endpoint_config = ENDPOINTS_CONFIG[endpoint]++ headers = {"Accept": "application/json"}+ if company_id:+ # Account API keys (seq_user_) span workspaces and need the target workspace+ # named per request; workspace keys (seq_live_) are already bound to one.+ headers["x-company-id"] = company_id++ config: RESTAPIConfig = {+ "client": {+ "base_url": SEQUENZY_BASE_URL,+ "auth": {+ "type": "bearer",+ "token": api_key,+ },+ "headers": headers,+ },+ "resource_defaults": {+ "write_disposition": "replace",+ },+ "resources": [get_resource(endpoint)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = _paginator_state(resume_config)++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if not state:+ return+ resumable_source_manager.save_state(+ SequenzyResumeConfig(+ cursor=state.get("cursor"),+ offset=state.get("offset"),+ page=state.get("page"),+ )+ )++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=list(endpoint_config.primary_keys),+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ # The paginated collections come back newest-first with no ascending option, and+ # the single-page collections document no order, so never claim "asc".+ sort_mode="desc",+ )+++def validate_credentials(api_key: str, company_id: str | None = None) -> tuple[bool, str | None]:+ # A non-ASCII key cannot be encoded into the Authorization header (requests uses+ # latin-1), which would otherwise surface a raw UnicodeEncodeError to the user.+ if not api_key.isascii():+ return (+ False,+ "Your Sequenzy API key contains an unsupported character (for example an invisible one "+ "pasted from another app). Retype it by hand and try again.",+ )++ headers = {"Authorization": f"Bearer {api_key}"}+ if company_id:+ headers["x-company-id"] = company_id++ # Documented by Sequenzy as the credential-validation endpoint for integrations.+ res = make_tracked_session(redact_values=(api_key,)).get(+ f"{SEQUENZY_BASE_URL}/subscribers/me",+ headers=headers,+ timeout=10,+ )+ if res.status_code == 200:+ return True, None+ if res.status_code == 401:+ return False, "Invalid API key. Check the key in Sequenzy under Settings > API Keys and try again."+ if res.status_code == 403:+ return (+ False,+ "Sequenzy could not find that workspace. If you use an account API key (seq_user_), "+ "enter the company ID of the workspace to sync.",+ )+ return False, f"Sequenzy returned an unexpected response (HTTP {res.status_code}). Try again later."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/settings.pynew file mode 100644index 000000000000..b20419380dbd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/settings.py@@ -0,0 +1,97 @@+from dataclasses import field+from typing import Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField++SEQUENZY_BASE_URL = "https://api.sequenzy.com/api/v1"+++@frozen+class SequenzyEndpointConfig:+ name: str+ path: str+ # Key of the row array in the response envelope ({"success": true, "<selector>": [...]}).+ data_selector: str+ pagination: Literal["cursor", "offset", "page", "single_page"]+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ partition_key: str | None = None+ page_size: int | None = None+ params: dict[str, str | int] = field(default_factory=dict)+++# Sequenzy paginates each collection differently: subscribers use an opaque cursor+# (`pagination.nextCursor`), campaigns and sequences use limit/offset, per-email metrics use+# page numbers, and the small definition collections (tags, lists, segments) return the whole+# collection in one response. Subscribers, campaigns, and sequences are returned newest-first+# with no way to request ascending order, hence sort_mode="desc" in sequenzy.py.+ENDPOINTS_CONFIG: dict[str, SequenzyEndpointConfig] = {+ "subscribers": SequenzyEndpointConfig(+ name="subscribers",+ path="/subscribers",+ data_selector="subscribers",+ pagination="cursor",+ page_size=1000,+ # `status=all` disables the default status filter so unsubscribed and bounced+ # contacts sync too. `includeTotal=false` skips the total-count query the API+ # otherwise runs for the first (cursorless) request.+ params={"status": "all", "includeTotal": "false"},+ partition_key="createdAt",+ ),+ "tags": SequenzyEndpointConfig(+ name="tags",+ path="/tags",+ data_selector="tags",+ pagination="single_page",+ ),+ "lists": SequenzyEndpointConfig(+ name="lists",+ path="/lists",+ data_selector="lists",+ pagination="single_page",+ ),+ "segments": SequenzyEndpointConfig(+ name="segments",+ path="/segments",+ data_selector="segments",+ pagination="single_page",+ ),+ "campaigns": SequenzyEndpointConfig(+ name="campaigns",+ path="/campaigns",+ data_selector="campaigns",+ pagination="offset",+ page_size=100,+ partition_key="createdAt",+ ),+ "sequences": SequenzyEndpointConfig(+ name="sequences",+ path="/sequences",+ data_selector="sequences",+ pagination="offset",+ page_size=100,+ partition_key="createdAt",+ ),+ "email_metrics": SequenzyEndpointConfig(+ name="email_metrics",+ path="/metrics/emails",+ data_selector="emails",+ pagination="page",+ page_size=500,+ # The default sort is `sent` desc, which reshuffles rows between pages as counts+ # move mid-sync. Name order is the most stable sort the endpoint offers.+ params={"sort": "name", "order": "asc"},+ # `emailId` is a campaign ID for campaign rows and an automation node ID for+ # sequence-step rows; the composite key guards against a collision across the+ # two ID namespaces.+ primary_keys=["emailType", "emailId"],+ ),+}++ENDPOINTS = tuple(ENDPOINTS_CONFIG.keys())++# The API exposes no server-side created/updated timestamp filter on any list endpoint+# (subscribers only filter on `unsubscribedAt`, which covers opted-out contacts alone),+# so every endpoint is full-refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/source.pyindex d12fbd1037d8..07a48b650b38 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/source.py@@ -1,28 +1,136 @@-from typing import cast+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+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.sequenzy import (SequenzySourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.sequenzy.sequenzy import (+ SequenzyResumeConfig,+ sequenzy_source,+ validate_credentials as validate_sequenzy_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sequenzy.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SequenzySource(SimpleSource[SequenzySourceConfig]):+class SequenzySource(ResumableSource[SequenzySourceConfig, SequenzyResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ api_docs_url = "https://docs.sequenzy.com/api-reference"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SEQUENZY+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your Sequenzy API key is invalid or was revoked. Create a new key in Sequenzy under Settings > API Keys and update the source.",+ "403 Client Error: Forbidden for url": "Your Sequenzy API key does not have access to this data. Check the key's permissions and the company ID, then try again.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.sequenzy.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SequenzySourceConfig,+ 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)++ def validate_credentials(+ self,+ config: SequenzySourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_sequenzy_credentials(config.api_key, config.company_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SequenzyResumeConfig]:+ return ResumableSourceManager[SequenzyResumeConfig](inputs, SequenzyResumeConfig)++ def source_for_pipeline(+ self,+ config: SequenzySourceConfig,+ resumable_source_manager: ResumableSourceManager[SequenzyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return sequenzy_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ company_id=config.company_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.SEQUENZY,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="Sequenzy",+ caption=(+ "Create an API key in Sequenzy under **Workspace Settings > API Keys** with read "+ "access to subscribers, tags, lists, segments, campaigns, sequences, and analytics."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/sequenzy",iconPath="/static/services/sequenzy.png",keywords=["email marketing", "newsletter"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="seq_live_...",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="company_id",+ label="Company ID",+ caption=(+ "Only needed with an account API key (starts with `seq_user_`): the ID of "+ "the Sequenzy workspace to sync. Workspace keys (`seq_live_`) already "+ "belong to one workspace."+ ),+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/tests/test_sequenzy.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/tests/test_sequenzy.pynew file mode 100644index 000000000000..b90641bda0da--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/tests/test_sequenzy.py@@ -0,0 +1,300 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.sequenzy.sequenzy import (+ SequenzyResumeConfig,+ _paginator_state,+ sequenzy_source,+ validate_credentials,+)++_SESSION_PATH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client"+ ".make_tracked_session"+)+++def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _drive(+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ company_id: str | None = None,+) -> tuple[MagicMock, list[dict[str, Any]], list[Any]]:+ """Drive ``sequenzy_source`` with a mocked HTTP session.++ Returns ``(mock_session, sent_params, rows)``. ``sent_params`` holds shallow copies+ of ``request.params`` captured at send-time, because the paginator mutates the+ Request object in place between pages.+ """+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(_SESSION_PATH) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ source_response = sequenzy_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ company_id=company_id,+ )+ # The resource yields one list of rows per page; flatten so assertions read per-row.+ pages = list(cast(Iterable[Any], source_response.items()))+ rows = [row for page in pages for row in (page if isinstance(page, list) else [page])]+ return mock_session, sent_params, rows+++def _manager(resume: SequenzyResumeConfig | None = None) -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++class TestSequenzyPagination:+ def test_subscribers_follow_next_cursor_until_null(self) -> None:+ manager = _manager()+ responses = [+ _make_http_response(+ {+ "success": True,+ "subscribers": [{"id": "sub_1", "email": "[email protected]"}],+ "pagination": {"nextCursor": "cur_1", "hasMore": True},+ }+ ),+ _make_http_response(+ {+ "success": True,+ "subscribers": [{"id": "sub_2", "email": "[email protected]"}],+ "pagination": {"nextCursor": "cur_2", "hasMore": True},+ }+ ),+ _make_http_response(+ {+ "success": True,+ "subscribers": [{"id": "sub_3", "email": "[email protected]"}],+ "pagination": {"nextCursor": None, "hasMore": False},+ }+ ),+ ]+ _, sent_params, rows = _drive("subscribers", manager, responses)++ assert [p.get("cursor") for p in sent_params] == [None, "cur_1", "cur_2"]+ assert [row["id"] for row in rows] == ["sub_1", "sub_2", "sub_3"]+ # The intermediate cursors are staged so a crash resumes mid-collection.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ SequenzyResumeConfig(cursor="cur_1"),+ SequenzyResumeConfig(cursor="cur_2"),+ ]++ def test_subscribers_request_shape(self) -> None:+ manager = _manager()+ responses = [+ _make_http_response(+ {+ "success": True,+ "subscribers": [{"id": "sub_1"}],+ "pagination": {"nextCursor": None, "hasMore": False},+ }+ ),+ ]+ _, sent_params, _ = _drive("subscribers", manager, responses)++ # `status=all` must go out or unsubscribed/bounced contacts silently never sync;+ # `includeTotal=false` skips the API's count query; page size rides as `limit`.+ assert sent_params[0]["status"] == "all"+ assert sent_params[0]["includeTotal"] == "false"+ assert sent_params[0]["limit"] == 1000++ def test_campaigns_offset_pagination_stops_at_total(self) -> None:+ manager = _manager()+ responses = [+ _make_http_response(+ {+ "success": True,+ "campaigns": [{"id": f"camp_{i}"} for i in range(100)],+ "pagination": {"limit": 100, "offset": 0, "count": 100, "total": 150, "hasMore": True},+ }+ ),+ _make_http_response(+ {+ "success": True,+ "campaigns": [{"id": f"camp_{i}"} for i in range(100, 150)],+ "pagination": {"limit": 100, "offset": 100, "count": 50, "total": 150, "hasMore": False},+ }+ ),+ ]+ _, sent_params, rows = _drive("campaigns", manager, responses)++ assert [(p.get("offset"), p.get("limit")) for p in sent_params] == [(0, 100), (100, 100)]+ assert len(rows) == 150++ def test_email_metrics_page_pagination_stops_at_total_pages(self) -> None:+ manager = _manager()+ responses = [+ _make_http_response(+ {+ "success": True,+ "emails": [{"emailType": "campaign", "emailId": "camp_1"}],+ "pagination": {"page": 1, "limit": 500, "total": 2, "totalPages": 2},+ }+ ),+ _make_http_response(+ {+ "success": True,+ "emails": [{"emailType": "sequence", "emailId": "node_1"}],+ "pagination": {"page": 2, "limit": 500, "total": 2, "totalPages": 2},+ }+ ),+ ]+ _, sent_params, rows = _drive("email_metrics", manager, responses)++ assert [p.get("page") for p in sent_params] == [1, 2]+ # A stable sort keeps rows from shuffling between pages while counts move mid-sync.+ assert sent_params[0]["sort"] == "name"+ assert sent_params[0]["order"] == "asc"+ assert len(rows) == 2++ @pytest.mark.parametrize("endpoint", ["tags", "lists", "segments"])+ def test_single_page_endpoints_make_one_request(self, endpoint: str) -> None:+ manager = _manager()+ responses = [+ _make_http_response({"success": True, endpoint: [{"id": f"{endpoint}_1", "name": "x"}]}),+ ]+ _, sent_params, rows = _drive(endpoint, manager, responses)++ assert len(sent_params) == 1+ assert [row["id"] for row in rows] == [f"{endpoint}_1"]+ manager.save_state.assert_not_called()+++class TestSequenzyResume:+ @pytest.mark.parametrize(+ ("endpoint", "resume", "param", "expected"),+ [+ ("subscribers", SequenzyResumeConfig(cursor="cur_saved"), "cursor", "cur_saved"),+ ("campaigns", SequenzyResumeConfig(offset=100), "offset", 100),+ ("email_metrics", SequenzyResumeConfig(page=2), "page", 2),+ ],+ )+ def test_resume_seeds_first_request(+ self, endpoint: str, resume: SequenzyResumeConfig, param: str, expected: Any+ ) -> None:+ manager = _manager(resume)+ selector = {"subscribers": "subscribers", "campaigns": "campaigns", "email_metrics": "emails"}[endpoint]+ responses = [+ _make_http_response({"success": True, selector: [], "pagination": {"nextCursor": None}}),+ ]+ _, sent_params, _ = _drive(endpoint, manager, responses)++ assert sent_params[0][param] == expected+ manager.load_state.assert_called_once()++ def test_terminal_single_page_does_not_save_state(self) -> None:+ manager = _manager()+ responses = [+ _make_http_response(+ {+ "success": True,+ "subscribers": [{"id": "only"}],+ "pagination": {"nextCursor": None, "hasMore": False},+ }+ ),+ ]+ _drive("subscribers", manager, responses)++ manager.save_state.assert_not_called()+ manager.load_state.assert_not_called()++ def test_paginator_state_drops_unset_fields(self) -> None:+ assert _paginator_state(SequenzyResumeConfig(cursor="c")) == {"cursor": "c"}+ assert _paginator_state(SequenzyResumeConfig(offset=200)) == {"offset": 200}+ assert _paginator_state(SequenzyResumeConfig()) is None+++class TestSequenzyCompanyHeader:+ def test_company_id_sets_workspace_header(self) -> None:+ manager = _manager()+ responses = [+ _make_http_response({"success": True, "tags": []}),+ ]+ mock_session, _, _ = _drive("tags", manager, responses, company_id="company_abc123")++ assert mock_session.headers.get("x-company-id") == "company_abc123"++ def test_no_company_id_sends_no_workspace_header(self) -> None:+ manager = _manager()+ responses = [+ _make_http_response({"success": True, "tags": []}),+ ]+ mock_session, _, _ = _drive("tags", manager, responses)++ assert "x-company-id" not in mock_session.headers+++class TestValidateCredentials:+ _SESSION = "products.warehouse_sources.backend.temporal.data_imports.sources.sequenzy.sequenzy.make_tracked_session"++ @pytest.mark.parametrize(+ ("status_code", "expected_valid", "expected_fragment"),+ [+ (200, True, None),+ (401, False, "Invalid API key"),+ (403, False, "company ID"),+ (500, False, "HTTP 500"),+ ],+ )+ def test_status_mapping(self, status_code: int, expected_valid: bool, expected_fragment: str | None) -> None:+ with patch(self._SESSION) as MockSession:+ MockSession.return_value.get.return_value = _make_http_response({}, status_code=status_code)+ valid, message = validate_credentials("seq_live_key")++ assert valid is expected_valid+ if expected_fragment is None:+ assert message is None+ else:+ assert expected_fragment in (message or "")++ def test_company_id_forwarded_as_header(self) -> None:+ with patch(self._SESSION) as MockSession:+ MockSession.return_value.get.return_value = _make_http_response({}, status_code=200)+ validate_credentials("seq_user_key", company_id="company_abc123")++ headers = MockSession.return_value.get.call_args.kwargs["headers"]+ assert headers["x-company-id"] == "company_abc123"++ def test_non_ascii_key_returns_actionable_message_without_a_request(self) -> None:+ # A non-latin-1 key can't be encoded into the Authorization header; the raw+ # UnicodeEncodeError must never surface to the user.+ with patch(self._SESSION) as MockSession:+ valid, message = validate_credentials("bad中key")++ assert valid is False+ assert "Retype it by hand" in (message or "")+ assert "latin-1" not in (message or "")+ MockSession.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/tests/test_sequenzy_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/tests/test_sequenzy_source.pynew file mode 100644index 000000000000..cf22f4f64d5b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sequenzy/tests/test_sequenzy_source.py@@ -0,0 +1,94 @@+import json+import dataclasses++import pytest+from unittest.mock import MagicMock++import requests++from products.warehouse_sources.backend.temporal.data_imports.sources.sequenzy.sequenzy import (+ SequenzyResumeConfig,+ sequenzy_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.sequenzy.source import SequenzySource+++class TestSequenzySourceNonRetryableErrors:+ @pytest.mark.parametrize(+ ("status_code", "reason"),+ [+ (401, "Unauthorized"),+ (403, "Forbidden"),+ ],+ )+ def test_auth_http_errors_match_a_non_retryable_pattern(self, status_code: int, reason: str) -> None:+ # The patterns must keep matching the exact message ``requests.raise_for_status``+ # produces, or bad credentials retry until the activity times out.+ response = requests.Response()+ response.status_code = status_code+ response.url = "https://api.sequenzy.com/api/v1/subscribers"+ response.reason = reason++ with pytest.raises(requests.HTTPError) as exc_info:+ response.raise_for_status()++ patterns = SequenzySource().get_non_retryable_errors()+ assert any(pattern in str(exc_info.value) for pattern in patterns)++ def test_server_errors_stay_retryable(self) -> None:+ response = requests.Response()+ response.status_code = 503+ response.url = "https://api.sequenzy.com/api/v1/subscribers"+ response.reason = "Service Unavailable"++ with pytest.raises(requests.HTTPError) as exc_info:+ response.raise_for_status()++ patterns = SequenzySource().get_non_retryable_errors()+ assert not any(pattern in str(exc_info.value) for pattern in patterns)+++class TestSequenzySourceResponse:+ def _source_response(self, endpoint: str):+ manager = MagicMock()+ manager.can_resume.return_value = False+ return sequenzy_source(+ api_key="key",+ endpoint=endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ )++ @pytest.mark.parametrize("endpoint", ["subscribers", "campaigns", "sequences"])+ def test_growing_collections_partition_on_created_at(self, endpoint: str) -> None:+ response = self._source_response(endpoint)++ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["createdAt"]++ @pytest.mark.parametrize("endpoint", ["tags", "lists", "segments", "email_metrics"])+ def test_unpartitionable_collections_get_no_partitioning(self, endpoint: str) -> None:+ response = self._source_response(endpoint)++ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_email_metrics_key_spans_both_id_namespaces(self) -> None:+ # `emailId` alone is a campaign ID for campaigns and an automation node ID for+ # sequence steps; a single-column key would multi-match on a collision and+ # merges would degrade every sync.+ response = self._source_response("email_metrics")++ assert response.primary_keys == ["emailType", "emailId"]+++class TestSequenzyResumeConfigRoundTrip:+ def test_round_trips_through_manager_serialization(self) -> None:+ # The manager serializes with dataclasses.asdict and reconstructs with+ # keyword arguments; a slotted/frozen config that breaks either would only+ # surface mid-sync in Temporal.+ original = SequenzyResumeConfig(cursor="cur_1")+ restored = SequenzyResumeConfig(**json.loads(json.dumps(dataclasses.asdict(original))))++ assert restored == original