: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 emailoctopus import source (#65642)
Tom Owers620ac190697e
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 90ddecdc9977..09eab97078aa 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -96,6 +96,7 @@ the row lists both.| freshsales | HTTP | requests | ✅ || elasticemail | HTTP | requests | ✅ || elasticsearch | HTTP | requests | ✅ |+| emailoctopus | HTTP | requests | ✅ || eventbrite | HTTP | requests | ✅ || front | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ |@@ -357,7 +358,6 @@ doesn't conflict with concurrent PRs.- easypromos- ebay- eloqua-- emailoctopus- employment_hero- encharge- eventeediff --git a/posthog/temporal/data_imports/sources/emailoctopus/canonical_descriptions.py b/posthog/temporal/data_imports/sources/emailoctopus/canonical_descriptions.pynew file mode 100644index 000000000000..bfe7502237e7--- /dev/null+++ b/posthog/temporal/data_imports/sources/emailoctopus/canonical_descriptions.py@@ -0,0 +1,48 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Curated from the EmailOctopus v2 API docs (https://emailoctopus.com/api-documentation/v2). The+# schema is fixed across teams, so document it once rather than paying an LLM to re-derive it.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "lists": {+ "description": "A list of contacts that campaigns and automations send to.",+ "docs_url": "https://emailoctopus.com/api-documentation/v2",+ "columns": {+ "id": "Unique identifier for the list.",+ "name": "Name of the list.",+ "double_opt_in": "Whether new contacts must confirm their subscription before being marked subscribed.",+ "fields": "Custom fields defined on the list, each with a tag, label, type and fallback.",+ "tags": "Tags configured on the list.",+ "counts": "Contact counts on the list, broken down by status (subscribed, unsubscribed, pending).",+ "created_at": "ISO 8601 timestamp of when the list was created.",+ },+ },+ "campaigns": {+ "description": "An email campaign sent to one or more lists.",+ "docs_url": "https://emailoctopus.com/api-documentation/v2",+ "columns": {+ "id": "Unique identifier for the campaign.",+ "status": "Current status of the campaign (e.g. draft, sending, sent).",+ "name": "Internal name of the campaign.",+ "subject": "Subject line of the campaign email.",+ "from": "Sender name and email address the campaign is sent from.",+ "to": "Lists the campaign is or was sent to.",+ "content": "Rendered HTML and plain-text content of the campaign.",+ "created_at": "ISO 8601 timestamp of when the campaign was created.",+ "sent_at": "ISO 8601 timestamp of when the campaign was sent, if it has been sent.",+ },+ },+ "contacts": {+ "description": "A contact belonging to a list, materialized one row per (list, contact). The list_id is attached to each row so a contact that appears on multiple lists stays distinct.",+ "docs_url": "https://emailoctopus.com/api-documentation/v2",+ "columns": {+ "id": "Identifier for the contact, an MD5 hash of the lowercase email address. Unique within a list.",+ "list_id": "Identifier of the list this contact belongs to.",+ "email_address": "Email address of the contact.",+ "fields": "Values of the list's custom fields for this contact.",+ "tags": "Tags applied to the contact.",+ "status": "Subscription status of the contact (subscribed, unsubscribed or pending).",+ "created_at": "ISO 8601 timestamp of when the contact was added to the list.",+ "last_updated_at": "ISO 8601 timestamp of when the contact was last updated.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/emailoctopus/emailoctopus.py b/posthog/temporal/data_imports/sources/emailoctopus/emailoctopus.pynew file mode 100644index 000000000000..e2507d2b1d7c--- /dev/null+++ b/posthog/temporal/data_imports/sources/emailoctopus/emailoctopus.py@@ -0,0 +1,349 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.emailoctopus.settings import (+ CONTACT_STATUSES,+ EMAILOCTOPUS_ENDPOINTS,+ EmailOctopusEndpointConfig,+)++EMAILOCTOPUS_BASE_URL = "https://api.emailoctopus.com"+# The v2 API caps a page at 100 results.+PAGE_SIZE = 100+++class EmailOctopusRetryableError(Exception):+ pass+++class EmailOctopusResumeConfig:+ # Full next-page URL returned by the API (`paging.next.url`). Followed verbatim so the original+ # query string — including any incremental time filter — is preserved across a resume. None means+ # "start this (list, status) pair at its first page".+ next_url: str | None = None+ # Fan-out bookmark: the list and contact status currently being paged. Stable identifiers (not a+ # positional index) so lists added/removed between a crash and the retry can't resume into the+ # wrong slice. None for the non-fan-out (lists/campaigns) endpoints.+ list_id: str | None = None+ status: str | None = None+ # The incremental filter frozen at the original run's start. Reused on resume so a watermark that+ # advanced mid-sync isn't re-applied to lists we haven't reached yet (which would skip their rows).+ incremental_field: str | None = None+ filter_value: str | None = None+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor value for EmailOctopus's ISO 8601 filters (e.g. 2024-01-19T12:14:28Z)."""+ if isinstance(value, datetime):+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ return str(value)+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": "application/json",+ }+++def _next_url(data: dict[str, Any]) -> str | None:+ """Extract `paging.next.url` from a v2 list response, or None when there are no more pages."""+ paging = data.get("paging") or {}+ nxt = paging.get("next") or {}+ return nxt.get("url")+++def validate_credentials(api_key: str) -> bool:+ url = f"{EMAILOCTOPUS_BASE_URL}/lists?{urlencode({'limit': 1})}"+ try:+ session = make_tracked_session(redact_values=(api_key,))+ response = session.get(url, headers=_get_headers(api_key), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++@retry(+ retry=retry_if_exception_type((EmailOctopusRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ params: dict[str, Any] | None = None,+) -> dict:+ response = session.get(url, headers=headers, params=params, timeout=60)++ # 429s carry an X-RateLimit-Retry-After header; the token bucket refills quickly (10/s), so an+ # exponential backoff retry recovers without parsing the header.+ if response.status_code == 429 or response.status_code >= 500:+ raise EmailOctopusRetryableError(+ f"EmailOctopus API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ # A 404 is expected when a list is deleted mid-fan-out; the caller handles it.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"EmailOctopus API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _iter_list_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[str]:+ """Page through /lists and yield each list's id, following the cursor links."""+ url = f"{EMAILOCTOPUS_BASE_URL}/lists"+ params: dict[str, Any] | None = {"limit": PAGE_SIZE}+ while True:+ data = _fetch_page(session, url, headers, logger, params)+ for item in data.get("data", []):+ yield item["id"]++ next_url = _next_url(data)+ if not next_url:+ break+ # Follow the full next-page URL verbatim; it already encodes the cursor and page size.+ url = next_url+ params = None+++def _build_contact_params(status: str, incremental_field: str | None, filter_value: str | None) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": PAGE_SIZE, "status": status}+ if incremental_field and filter_value:+ # Server-side incremental filter, e.g. last_updated_at.gte=2024-01-19T12:14:28Z.+ params[f"{incremental_field}.gte"] = filter_value+ return params+++def _get_top_level_rows(+ session: requests.Session,+ config: EmailOctopusEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[EmailOctopusResumeConfig],+) -> Iterator[Any]:+ resume = manager.load_state() if manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = resume.next_url+ params: dict[str, Any] | None = None+ logger.debug(f"EmailOctopus: resuming {config.name} from URL: {url}")+ else:+ url = f"{EMAILOCTOPUS_BASE_URL}{config.path}"+ params = {"limit": PAGE_SIZE}++ while True:+ data = _fetch_page(session, url, headers, logger, params)+ items = data.get("data", [])+ next_url = _next_url(data)++ for item in items:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding (and only while more pages remain) so a crash re-yields the last+ # page rather than skipping it — merge dedupes on the primary key.+ if next_url:+ manager.save_state(EmailOctopusResumeConfig(next_url=next_url))++ if not next_url:+ break+ url = next_url+ params = None+++def _get_contact_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[EmailOctopusResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> Iterator[Any]:+ """Fan out over every list and contact status, yielding each contact with its `list_id` attached.++ Contacts are nested under lists and the API returns only one status at a time, so we walk every+ (list, status) pair. The [list_id, id] primary key keeps a single row per contact across statuses.+ """+ list_ids = list(_iter_list_ids(session, headers, logger))+ pairs = [(list_id, status) for list_id in list_ids for status in CONTACT_STATUSES]++ resume = manager.load_state() if manager.can_resume() else None+ if resume is not None:+ # Reuse the filter frozen at the original run's start. The incremental watermark can advance+ # mid-sync; recomputing it here would over-filter lists we haven't reached yet.+ filter_field = resume.incremental_field+ filter_value = resume.filter_value+ else:+ filter_field = incremental_field if should_use_incremental_field else None+ filter_value = (+ _format_incremental_value(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value and incremental_field+ else None+ )++ # Resolve the saved (list_id, status) bookmark to the remaining slice. If the bookmarked list no+ # longer exists, start over from the first pair — merge dedupes the re-pulled rows.+ start = 0+ resume_url: str | None = None+ if resume is not None and resume.list_id is not None and resume.status is not None:+ try:+ start = pairs.index((resume.list_id, resume.status))+ resume_url = resume.next_url+ logger.debug(f"EmailOctopus: resuming contacts from list_id={resume.list_id}, status={resume.status}")+ except ValueError:+ start = 0+ remaining = pairs[start:]++ for index, (list_id, status) in enumerate(remaining):+ if index == 0 and resume_url:+ url = resume_url+ params: dict[str, Any] | None = None+ else:+ url = f"{EMAILOCTOPUS_BASE_URL}/lists/{list_id}/contacts"+ params = _build_contact_params(status, filter_field, filter_value)++ try:+ while True:+ data = _fetch_page(session, url, headers, logger, params)+ items = data.get("data", [])+ next_url = _next_url(data)++ for item in items:+ item["list_id"] = list_id+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ if next_url:+ manager.save_state(+ EmailOctopusResumeConfig(+ next_url=next_url,+ list_id=list_id,+ status=status,+ incremental_field=filter_field,+ filter_value=filter_value,+ )+ )++ if not next_url:+ break+ url = next_url+ params = None+ except requests.HTTPError as exc:+ # A list deleted between enumeration and this fetch 404s. Skip it rather than failing the+ # whole sync — the membership is genuinely gone. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"EmailOctopus: list {list_id} not found while fetching contacts, skipping")+ else:+ raise++ # Flush residual batcher items before advancing the bookmark so a crash between pairs can't+ # silently drop rows that are buffered (below a full chunk) but not yet yielded — on resume we+ # start at the next pair and would never re-fetch them.+ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()++ # Advance the bookmark to the next pair so a crash between pairs resumes correctly; its first+ # page is built fresh (next_url=None) when the loop reaches it.+ if index + 1 < len(remaining):+ next_list_id, next_status = remaining[index + 1]+ manager.save_state(+ EmailOctopusResumeConfig(+ next_url=None,+ list_id=next_list_id,+ status=next_status,+ incremental_field=filter_field,+ filter_value=filter_value,+ )+ )+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[EmailOctopusResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = EMAILOCTOPUS_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page (and, for fan-out, every list) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. Redact the API key so it can't leak+ # into logged URLs or sampled requests via the Bearer auth header.+ session = make_tracked_session(redact_values=(api_key,))++ if config.fan_out_over_lists:+ yield from _get_contact_rows(+ session,+ headers,+ logger,+ batcher,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ incremental_field,+ )+ else:+ yield from _get_top_level_rows(session, config, headers, logger, batcher, resumable_source_manager)++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def emailoctopus_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[EmailOctopusResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = EMAILOCTOPUS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ # The v2 contacts endpoint paginates with an opaque cursor and does not document an ascending+ # sort guarantee. "asc" is the safe default: the incremental fields are monotonic wall-clock+ # timestamps, and the resumable cursor (not the watermark) drives mid-sync continuation.+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/emailoctopus/settings.py b/posthog/temporal/data_imports/sources/emailoctopus/settings.pynew file mode 100644index 000000000000..22f75343564f--- /dev/null+++ b/posthog/temporal/data_imports/sources/emailoctopus/settings.py@@ -0,0 +1,73 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class EmailOctopusEndpointConfig:+ name: str+ # Path on the v2 API. For fan-out endpoints this is a template with a `{list_id}` placeholder.+ path: str+ incremental_fields: list[IncrementalField]+ # A stable creation-time field used for datetime partitioning. Never `last_updated_at`,+ # which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ # Fan out one paginated request per synced list, materializing each list's contacts. When True,+ # `path` is a template with a `{list_id}` placeholder and rows carry their `list_id`.+ fan_out_over_lists: bool = False+++# EmailOctopus contacts carry a status and the API returns only `subscribed` contacts unless asked+# otherwise, so we iterate every status to capture the full membership. A contact's id is stable+# across status changes, so merge on [list_id, id] keeps a single row per contact reflecting its+# latest status.+CONTACT_STATUSES = ("subscribed", "unsubscribed", "pending")+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++EMAILOCTOPUS_ENDPOINTS: dict[str, EmailOctopusEndpointConfig] = {+ "lists": EmailOctopusEndpointConfig(+ name="lists",+ path="/lists",+ partition_key="created_at",+ # No server-side timestamp filter on /lists, so full refresh only.+ incremental_fields=[],+ ),+ "campaigns": EmailOctopusEndpointConfig(+ name="campaigns",+ path="/campaigns",+ partition_key="created_at",+ # No server-side timestamp filter on /campaigns, so full refresh only.+ incremental_fields=[],+ ),+ # Contacts are nested under lists. The endpoint exposes genuine server-side filters+ # (`created_at.gte`, `last_updated_at.gte`), so incremental sync is real here.+ "contacts": EmailOctopusEndpointConfig(+ name="contacts",+ path="/lists/{list_id}/contacts",+ partition_key="created_at",+ primary_keys=["list_id", "id"],+ fan_out_over_lists=True,+ incremental_fields=[+ _datetime_field("last_updated_at"),+ _datetime_field("created_at"),+ ],+ ),+}++ENDPOINTS = tuple(EMAILOCTOPUS_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in EMAILOCTOPUS_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/emailoctopus/source.py b/posthog/temporal/data_imports/sources/emailoctopus/source.pyindex 3063e0fcd46a..313a6b9dbd7c 100644--- a/posthog/temporal/data_imports/sources/emailoctopus/source.py+++ b/posthog/temporal/data_imports/sources/emailoctopus/source.py@@ -1,20 +1,37 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchema+from posthog.temporal.data_imports.sources.emailoctopus.emailoctopus import (+ EmailOctopusResumeConfig,+ emailoctopus_source,+ validate_credentials as validate_emailoctopus_credentials,+)+from posthog.temporal.data_imports.sources.emailoctopus.settings import (+ EMAILOCTOPUS_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from posthog.temporal.data_imports.sources.generated_configs import EmailOctopusSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class EmailOctopusSource(SimpleSource[EmailOctopusSourceConfig]):+class EmailOctopusSource(ResumableSource[EmailOctopusSourceConfig, EmailOctopusResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.EMAILOCTOPUS@@ -25,7 +42,92 @@ class EmailOctopusSource(SimpleSource[EmailOctopusSourceConfig]):name=SchemaExternalDataSourceType.EMAIL_OCTOPUS,category=DataWarehouseSourceCategory.MARKETING___EMAIL,label="EmailOctopus",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your EmailOctopus API key to automatically pull your EmailOctopus data into the PostHog Data warehouse.++You can create an API key in your [EmailOctopus account settings](https://emailoctopus.com/api-documentation). The key grants account-wide read access.""",iconPath="/static/services/emailoctopus.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/emailoctopus",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="eo_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.emailoctopus.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked EmailOctopus API key surfaces as a requests HTTPError when+ # `_fetch_page` calls `raise_for_status()`. Retrying can never satisfy a credential+ # problem, so stop the sync. Match the stable status text and base host, not the+ # per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.emailoctopus.com": "Your EmailOctopus API key is invalid or has been revoked. Create a new API key in your EmailOctopus account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.emailoctopus.com": "Your EmailOctopus API key does not have permission to access this data. Check the key in your EmailOctopus account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: EmailOctopusSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ incremental_fields = INCREMENTAL_FIELDS.get(endpoint, [])+ has_incremental = len(incremental_fields) > 0+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=incremental_fields,+ should_sync_default=EMAILOCTOPUS_ENDPOINTS[endpoint].should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: EmailOctopusSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_emailoctopus_credentials(config.api_key):+ return True, None++ return False, "Invalid EmailOctopus API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EmailOctopusResumeConfig]:+ return ResumableSourceManager[EmailOctopusResumeConfig](inputs, EmailOctopusResumeConfig)++ def source_for_pipeline(+ self,+ config: EmailOctopusSourceConfig,+ resumable_source_manager: ResumableSourceManager[EmailOctopusResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return emailoctopus_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus.py b/posthog/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus.pynew file mode 100644index 000000000000..bd3a083b63ef--- /dev/null+++ b/posthog/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus.py@@ -0,0 +1,387 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from posthog.temporal.data_imports.sources.emailoctopus import emailoctopus+from posthog.temporal.data_imports.sources.emailoctopus.emailoctopus import (+ EMAILOCTOPUS_BASE_URL as BASE,+ EmailOctopusResumeConfig,+ _build_contact_params,+ _format_incremental_value,+ _get_headers,+ _next_url,+ emailoctopus_source,+ get_rows,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.emailoctopus.settings import EMAILOCTOPUS_ENDPOINTS+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("microseconds_dropped", datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45Z"),+ ("naive_datetime_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2024-01-19T12:14:28Z", "2024-01-19T12:14:28Z"),+ ]+ )+ def test_format(self, _name: str, value: object, expected: str) -> None:+ assert _format_incremental_value(value) == expected++ def test_no_offset_suffix(self) -> None:+ # EmailOctopus's ISO 8601 filters use a Z suffix, never the +00:00 offset isoformat() emits.+ result = _format_incremental_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+ assert "+00:00" not in result+ assert result.endswith("Z")+++class TestNextUrl:+ @parameterized.expand(+ [+ (+ "has_next",+ {"paging": {"next": {"url": f"{BASE}/lists?starting_after=abc&limit=100"}}},+ f"{BASE}/lists?starting_after=abc&limit=100",+ ),+ ("next_is_null", {"paging": {"next": None}}, None),+ ("no_next_key", {"paging": {}}, None),+ ("no_paging_key", {"data": []}, None),+ ("paging_is_null", {"paging": None}, None),+ ]+ )+ def test_next_url(self, _name: str, data: dict, expected: str | None) -> None:+ assert _next_url(data) == expected+++class TestHeaders:+ def test_bearer_token(self) -> None:+ headers = _get_headers("eo_secret")+ assert headers["Authorization"] == "Bearer eo_secret"+ assert headers["Accept"] == "application/json"+++class TestBuildContactParams:+ def test_status_only_when_no_incremental(self) -> None:+ params = _build_contact_params("subscribed", incremental_field=None, filter_value=None)+ assert params == {"limit": 100, "status": "subscribed"}++ def test_no_filter_when_value_missing(self) -> None:+ params = _build_contact_params("pending", incremental_field="created_at", filter_value=None)+ assert "created_at.gte" not in params++ @parameterized.expand(+ [+ ("last_updated", "last_updated_at", "last_updated_at.gte"),+ ("created", "created_at", "created_at.gte"),+ ]+ )+ def test_server_side_filter(self, _name: str, field: str, expected_param: str) -> None:+ params = _build_contact_params("subscribed", incremental_field=field, filter_value="2026-01-01T00:00:00Z")+ assert params[expected_param] == "2026-01-01T00:00:00Z"+ assert params["status"] == "subscribed"+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status_code+ session = MagicMock()+ session.get.return_value = response+ with patch.object(emailoctopus, "make_tracked_session", return_value=session):+ assert validate_credentials("eo_key") is expected++ def test_network_error_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with patch.object(emailoctopus, "make_tracked_session", return_value=session):+ assert validate_credentials("eo_key") is False++ def test_tracked_session_redacts_api_key(self) -> None:+ response = MagicMock()+ response.status_code = 200+ session = MagicMock()+ session.get.return_value = response+ with patch.object(emailoctopus, "make_tracked_session", return_value=session) as make_session:+ validate_credentials("eo_secret")+ # The key must be passed as a redaction value so it can't leak into tracked HTTP logs.+ make_session.assert_called_once_with(redact_values=("eo_secret",))+++class _FakeResumableManager:+ def __init__(self, state: EmailOctopusResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[EmailOctopusResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> EmailOctopusResumeConfig | None:+ return self._state++ def save_state(self, data: EmailOctopusResumeConfig) -> None:+ self.saved.append(data)+++def _response_with_status(status_code: int) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ return response+++def _make_fake_fetch(pages: dict[str, Any], calls: list[tuple[str, Any]] | None = None):+ """Route a fetch to a canned response, keyed by url (plus status param for the contacts first page)."""++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any, params: Any = None) -> dict:+ if calls is not None:+ calls.append((url, params))+ key = url+ if params and "status" in params:+ key = f"{url}?status={params['status']}"+ result = pages[key]+ if isinstance(result, Exception):+ raise result+ return result++ return fake_fetch+++def _collect(+ endpoint: str, manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], **kwargs: Any+) -> list[dict]:+ monkeypatch.setattr(emailoctopus, "_fetch_page", _make_fake_fetch(pages))+ rows: list[dict] = []+ for table in get_rows(+ api_key="eo_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(table.to_pylist())+ return rows+++class TestTopLevelRows:+ def test_paginates_following_next_url(self, monkeypatch: Any) -> None:+ next_url = f"{BASE}/lists?starting_after=cur1&limit=100"+ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}], "paging": {"next": {"url": next_url}}},+ next_url: {"data": [{"id": "L2"}], "paging": {"next": None}},+ }+ rows = _collect("lists", _FakeResumableManager(), monkeypatch, pages)+ assert rows == [{"id": "L1"}, {"id": "L2"}]++ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:+ resume_url = f"{BASE}/campaigns?starting_after=cur5&limit=100"+ pages = {resume_url: {"data": [{"id": "C9"}], "paging": {"next": None}}}+ manager = _FakeResumableManager(EmailOctopusResumeConfig(next_url=resume_url))+ rows = _collect("campaigns", manager, monkeypatch, pages)+ # The initial /campaigns URL is never fetched — we jump straight to the saved cursor.+ assert rows == [{"id": "C9"}]+++class TestContactsFanOut:+ def test_fans_out_over_lists_and_statuses_attaching_list_id(self, monkeypatch: Any) -> None:+ # One list, three statuses; each status query returns one contact.+ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=subscribed": {"data": [{"id": "c-sub"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=unsubscribed": {"data": [{"id": "c-unsub"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=pending": {"data": [{"id": "c-pend"}], "paging": {"next": None}},+ }+ rows = _collect("contacts", _FakeResumableManager(), monkeypatch, pages)+ assert rows == [+ {"id": "c-sub", "list_id": "L1"},+ {"id": "c-unsub", "list_id": "L1"},+ {"id": "c-pend", "list_id": "L1"},+ ]++ def test_applies_server_side_incremental_filter_on_first_page(self, monkeypatch: Any) -> None:+ calls: list[tuple[str, Any]] = []+ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=subscribed": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=unsubscribed": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=pending": {"data": [], "paging": {"next": None}},+ }+ monkeypatch.setattr(emailoctopus, "_fetch_page", _make_fake_fetch(pages, calls))+ list(+ get_rows(+ api_key="eo_key",+ endpoint="contacts",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ incremental_field="last_updated_at",+ )+ )+ contact_calls = [params for url, params in calls if "contacts" in url]+ assert all(params["last_updated_at.gte"] == "2026-01-01T00:00:00Z" for params in contact_calls)++ def test_no_filter_on_first_sync_without_watermark(self, monkeypatch: Any) -> None:+ calls: list[tuple[str, Any]] = []+ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=subscribed": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=unsubscribed": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=pending": {"data": [], "paging": {"next": None}},+ }+ monkeypatch.setattr(emailoctopus, "_fetch_page", _make_fake_fetch(pages, calls))+ list(+ get_rows(+ api_key="eo_key",+ endpoint="contacts",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="last_updated_at",+ )+ )+ contact_calls = [params for url, params in calls if "contacts" in url]+ assert all("last_updated_at.gte" not in params for params in contact_calls)++ def test_list_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:+ not_found = requests.HTTPError(response=_response_with_status(404))+ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}, {"id": "GONE"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=subscribed": {"data": [{"id": "c1"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=unsubscribed": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=pending": {"data": [], "paging": {"next": None}},+ # A deleted list 404s independently for each status query; all are skipped.+ f"{BASE}/lists/GONE/contacts?status=subscribed": not_found,+ f"{BASE}/lists/GONE/contacts?status=unsubscribed": not_found,+ f"{BASE}/lists/GONE/contacts?status=pending": not_found,+ }+ rows = _collect("contacts", _FakeResumableManager(), monkeypatch, pages)+ assert rows == [{"id": "c1", "list_id": "L1"}]++ def test_non_404_error_propagates(self, monkeypatch: Any) -> None:+ server_error = requests.HTTPError(response=_response_with_status(500))+ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=subscribed": server_error,+ }+ with pytest.raises(requests.HTTPError):+ _collect("contacts", _FakeResumableManager(), monkeypatch, pages)++ def test_buffered_rows_flushed_before_advancing_pair_bookmark(self, monkeypatch: Any) -> None:+ # A crash right after the bookmark advances to the next list must not lose rows still+ # buffered (below a full chunk) from the previous list — so they must be yielded first.+ events: list[tuple[str, Any]] = []++ class _RecordingManager(_FakeResumableManager):+ def save_state(self, data: EmailOctopusResumeConfig) -> None:+ super().save_state(data)+ events.append(("save", (data.list_id, data.status, data.next_url)))++ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}, {"id": "L2"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=subscribed": {"data": [{"id": "a"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=unsubscribed": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=pending": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L2/contacts?status=subscribed": {"data": [{"id": "b"}], "paging": {"next": None}},+ f"{BASE}/lists/L2/contacts?status=unsubscribed": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L2/contacts?status=pending": {"data": [], "paging": {"next": None}},+ }+ manager = _RecordingManager()+ monkeypatch.setattr(emailoctopus, "_fetch_page", _make_fake_fetch(pages))+ for table in get_rows(+ api_key="eo_key",+ endpoint="contacts",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ for row in table.to_pylist():+ events.append(("row", row["id"]))++ l1_row = events.index(("row", "a"))+ advance_to_l2 = next(+ i for i, (kind, payload) in enumerate(events) if kind == "save" and payload[:2] == ("L2", "subscribed")+ )+ assert l1_row < advance_to_l2++ def test_resume_from_deleted_bookmark_restarts(self, monkeypatch: Any) -> None:+ # Bookmark points at a list that no longer exists -> start over from the first pair.+ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=subscribed": {"data": [{"id": "c1"}], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=unsubscribed": {"data": [], "paging": {"next": None}},+ f"{BASE}/lists/L1/contacts?status=pending": {"data": [], "paging": {"next": None}},+ }+ manager = _FakeResumableManager(EmailOctopusResumeConfig(list_id="DELETED", status="subscribed", next_url=None))+ rows = _collect("contacts", manager, monkeypatch, pages)+ assert rows == [{"id": "c1", "list_id": "L1"}]+++class TestResumeStateSaving:+ def test_saves_next_url_after_yielding_when_more_pages_remain(self, monkeypatch: Any) -> None:+ # Force a yield per row by shrinking the batcher thresholds.+ next_url = f"{BASE}/lists?starting_after=cur1&limit=100"+ pages = {+ f"{BASE}/lists": {"data": [{"id": "L1"}], "paging": {"next": {"url": next_url}}},+ next_url: {"data": [{"id": "L2"}], "paging": {"next": None}},+ }+ manager = _FakeResumableManager()+ monkeypatch.setattr(emailoctopus, "_fetch_page", _make_fake_fetch(pages))++ class _ImmediateBatcher:+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self._rows: list[dict] = []++ def batch(self, row: dict) -> None:+ self._rows.append(row)++ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:+ return len(self._rows) > 0++ def get_table(self) -> Any:+ table = MagicMock()+ rows = list(self._rows)+ table.to_pylist.return_value = rows+ self._rows = []+ return table++ monkeypatch.setattr(emailoctopus, "Batcher", _ImmediateBatcher)+ list(+ get_rows(+ api_key="eo_key",+ endpoint="lists",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ )+ )+ # The first page has a next URL, so its cursor is saved; the last page does not.+ assert any(s.next_url == next_url for s in manager.saved)+++class TestSourceResponse:+ @parameterized.expand(+ [+ ("lists", ["id"]),+ ("campaigns", ["id"]),+ ("contacts", ["list_id", "id"]),+ ]+ )+ def test_primary_keys_and_partitioning(self, endpoint: str, expected_pks: list[str]) -> None:+ response = emailoctopus_source(+ api_key="eo_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_pks+ assert response.sort_mode == "asc"+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [EMAILOCTOPUS_ENDPOINTS[endpoint].partition_key]+ assert EMAILOCTOPUS_ENDPOINTS[endpoint].partition_key == "created_at"diff --git a/posthog/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus_source.py b/posthog/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus_source.pynew file mode 100644index 000000000000..45079d2af387--- /dev/null+++ b/posthog/temporal/data_imports/sources/emailoctopus/tests/test_emailoctopus_source.py@@ -0,0 +1,142 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.emailoctopus import source as source_module+from posthog.temporal.data_imports.sources.emailoctopus.emailoctopus import EmailOctopusResumeConfig+from posthog.temporal.data_imports.sources.emailoctopus.source import EmailOctopusSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _config() -> Any:+ config = MagicMock()+ config.api_key = "eo_key"+ return config+++class TestEmailOctopusSourceConfig:+ def test_source_type(self) -> None:+ assert EmailOctopusSource().source_type == ExternalDataSourceType.EMAILOCTOPUS++ def test_source_config_basics(self) -> None:+ config = EmailOctopusSource().get_source_config+ assert config.name == SchemaExternalDataSourceType.EMAIL_OCTOPUS+ assert config.label == "EmailOctopus"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible: no unreleasedSource flag.+ assert not config.unreleasedSource++ def test_api_key_field_is_a_required_secret(self) -> None:+ fields = EmailOctopusSource().get_source_config.fields+ api_key_fields = [f for f in fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key"]+ assert len(api_key_fields) == 1+ api_key = api_key_fields[0]+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.required is True+ assert api_key.secret is True+++class TestEmailOctopusGetSchemas:+ def test_returns_all_endpoints(self) -> None:+ names = {s.name for s in EmailOctopusSource().get_schemas(_config(), team_id=1)}+ assert names == {"lists", "campaigns", "contacts"}++ @parameterized.expand(+ [+ ("lists", False),+ ("campaigns", False),+ ("contacts", True),+ ]+ )+ def test_incremental_support(self, endpoint: str, supports_incremental: bool) -> None:+ schemas = {s.name: s for s in EmailOctopusSource().get_schemas(_config(), team_id=1)}+ assert schemas[endpoint].supports_incremental is supports_incremental++ def test_contacts_incremental_fields(self) -> None:+ schemas = {s.name: s for s in EmailOctopusSource().get_schemas(_config(), team_id=1)}+ fields = {f["field"] for f in schemas["contacts"].incremental_fields}+ assert fields == {"created_at", "last_updated_at"}++ def test_names_filter(self) -> None:+ schemas = EmailOctopusSource().get_schemas(_config(), team_id=1, names=["contacts"])+ assert [s.name for s in schemas] == ["contacts"]+++class TestEmailOctopusValidateCredentials:+ @parameterized.expand([("valid", True), ("invalid", False)])+ def test_validate(self, _name: str, is_valid: bool) -> None:+ with patch.object(source_module, "validate_emailoctopus_credentials", return_value=is_valid):+ ok, message = EmailOctopusSource().validate_credentials(_config(), team_id=1)+ assert ok is is_valid+ assert (message is None) is is_valid+++class TestEmailOctopusNonRetryableErrors:+ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.emailoctopus.com/lists?limit=1"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.emailoctopus.com/campaigns"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = EmailOctopusSource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.emailoctopus.com/lists"),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.emailoctopus.com/lists"),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = EmailOctopusSource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestEmailOctopusResumableAndPipeline:+ def _inputs(self, schema_name: str) -> SourceInputs:+ return SourceInputs(+ 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=MagicMock(),+ reset_pipeline=False,+ )++ def test_resumable_manager_bound_to_resume_config(self) -> None:+ manager = EmailOctopusSource().get_resumable_source_manager(self._inputs("contacts"))+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is EmailOctopusResumeConfig++ def test_source_for_pipeline_plumbs_endpoint(self) -> None:+ inputs = self._inputs("contacts")+ manager = EmailOctopusSource().get_resumable_source_manager(inputs)+ response = EmailOctopusSource().source_for_pipeline(_config(), manager, inputs)+ assert response.name == "contacts"+ assert response.primary_keys == ["list_id", "id"]+++class TestEmailOctopusCanonicalDescriptions:+ def test_documents_every_endpoint(self) -> None:+ descriptions = EmailOctopusSource().get_canonical_descriptions()+ assert set(descriptions.keys()) == {"lists", "campaigns", "contacts"}+ assert "list_id" in descriptions["contacts"]["columns"]diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 0ee54fc00e74..51c231992757 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1018,7 +1018,7 @@ class EloquaSourceConfig(config.Config):@config.configclass EmailOctopusSourceConfig(config.Config):- pass+ api_key: str@config.config