: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 smartlead import source (#107259)
Tom Owers3bb51b1a770b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 04829123d04c..cb669cfae023 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -654,6 +654,7 @@ the row lists both.| sleekplan | HTTP | requests + `rest_source.RESTClient` | ✅ || smaily | HTTP | requests | ✅ || smartengage | HTTP | requests + `rest_source.RESTClient` | ✅ |+| smartlead | HTTP | requests + `rest_source.RESTClient` | ✅ || smartreach | HTTP | requests | ✅ || smartsheet | HTTP | requests | ✅ || smartwaiver | HTTP | requests | ✅ |@@ -1385,7 +1386,6 @@ doesn't conflict with concurrent PRs.- slash- sleuth- smaily-- smartlead- smartlook- smartrecruiters- smartwaiverdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.pyindex 7706b67c6e84..d1965cdb0db3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/sample_scrub.py@@ -49,6 +49,11 @@ REDACT_FIELD_NAMES: frozenset[str] = frozenset(# either grants terminal access, so keep them out of captured HTTP samples too."jupyter_token","jupyter_url",+ # Smartlead's email-accounts endpoint returns mailbox SMTP/IMAP credentials under this+ # key; `password` above already covers the SMTP field, but the IMAP one has a distinct+ # name and would otherwise reach captured samples raw (the source's own `redact_fields`+ # strips it from synced rows, but that runs after, not before, sample capture).+ "imap_password",})diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartlead.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartlead.pyindex 6efd4ec33507..4228f9a62adb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartlead.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/smartlead.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SmartleadSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/canonical_descriptions.pynew file mode 100644index 000000000000..48969545b93b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/canonical_descriptions.py@@ -0,0 +1,127 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "campaigns": {+ "description": "A cold email outreach campaign with its status, sending schedule, tracking settings, and sending limits.",+ "docs_url": "https://api.smartlead.ai/api-reference/campaigns/get-all",+ "columns": {+ "id": "Unique campaign identifier.",+ "user_id": "ID of the Smartlead user who owns this campaign.",+ "name": "Campaign name set by the user.",+ "status": "Current campaign status: ACTIVE, PAUSED, STOPPED, ARCHIVED, or DRAFTED.",+ "created_at": "ISO 8601 timestamp when the campaign was created.",+ "updated_at": "ISO 8601 timestamp of the last modification.",+ "track_settings": "Tracking configuration flags, e.g. DONT_EMAIL_OPEN or DONT_LINK_CLICK.",+ "scheduler_cron_value": "Sending schedule: timezone, days of week, and start/end hours.",+ "min_time_btwn_emails": "Minimum minutes to wait between consecutive emails.",+ "max_leads_per_day": "Maximum number of leads to contact per day across all email accounts.",+ "stop_lead_settings": "When to stop emailing a lead: REPLY_TO_AN_EMAIL, OPENED_EMAIL, CLICKED_LINK, or NEVER.",+ "schedule_start_time": "Scheduled start time for the campaign, null if starting immediately.",+ "enable_ai_esp_matching": "Whether Smartlead's AI matches leads with email accounts by provider.",+ "send_as_plain_text": "Whether emails are sent as plain text instead of HTML.",+ "follow_up_percentage": "Percentage of leads that receive follow-up emails (0-100).",+ "parent_campaign_id": "Parent campaign ID when this is a subsequence, null for main campaigns.",+ "client_id": "Associated client ID for agency accounts, null for direct user campaigns.",+ },+ },+ "campaign_sequences": {+ "description": "An email sequence step configured in a campaign, including subject, body, delay, and A/B test variants.",+ "docs_url": "https://api.smartlead.ai/api-reference/campaigns/get-sequences",+ "columns": {+ "id": "Unique sequence step identifier.",+ "campaign_id": "ID of the campaign this sequence step belongs to.",+ "email_campaign_id": "ID of the campaign as reported by the sequence record itself.",+ "seq_number": "Position of this step in the sequence (1, 2, 3, ...).",+ "subject": "Email subject line, may include template variables.",+ "follow_up_subject": "Subject a follow-up step actually sends with, inherited from the most recent earlier step that set one.",+ "email_body": "Email content as HTML or plain text.",+ "seq_delay_details": "Delay configuration, including days to wait before sending this step.",+ "sequence_variants": "A/B test variants for this step, each with its own subject and body.",+ "created_at": "ISO 8601 timestamp when the sequence step was created.",+ "updated_at": "ISO 8601 timestamp of the last modification.",+ },+ },+ "campaign_leads": {+ "description": "A lead's membership in a campaign, with the lead's contact details and campaign-specific status.",+ "docs_url": "https://api.smartlead.ai/api-reference/leads/get-by-campaign",+ "columns": {+ "campaign_lead_map_id": "Unique identifier for the lead-to-campaign mapping.",+ "campaign_id": "ID of the campaign the lead belongs to.",+ "lead_category_id": "Category ID assigned to this lead, null if uncategorized.",+ "status": "Lead status in this campaign: STARTED, INPROGRESS, COMPLETED, PAUSED, or STOPPED.",+ "created_at": "ISO 8601 timestamp when the lead was added to the campaign.",+ "lead": "Lead contact details: email, name, company, phone, location, LinkedIn profile, and custom fields.",+ },+ },+ "campaign_statistics": {+ "description": "Per-email send statistics for a campaign: one row per sent email with open, click, reply, and bounce outcomes.",+ "docs_url": "https://api.smartlead.ai/api-reference/campaigns/statistics",+ "columns": {+ "stats_id": "Unique identifier of the sent-email statistics record.",+ "campaign_id": "ID of the campaign the email was sent from.",+ "lead_name": "Recipient lead's full name.",+ "lead_email": "Recipient lead's email address.",+ "sequence_number": "Which sequence step the email belongs to (1, 2, 3, ...).",+ "email_subject": "Subject of the sent email.",+ "sent_time": "When the email was sent.",+ "open_time": "When the email was first opened, null if never opened.",+ "click_time": "When a link was first clicked, null if never clicked.",+ "reply_time": "When the lead replied, null if no reply.",+ "open_count": "Number of times the email was opened.",+ "click_count": "Number of times a link in the email was clicked.",+ "is_unsubscribed": "Whether the lead unsubscribed from this email.",+ "is_bounced": "Whether the email bounced.",+ },+ },+ "campaign_analytics": {+ "description": "Aggregate performance metrics for a campaign: totals and rates for sends, opens, clicks, replies, and bounces.",+ "docs_url": "https://api.smartlead.ai/api-reference/campaigns/get-analytics",+ "columns": {+ "campaign_id": "ID of the campaign the metrics belong to.",+ "total_sent": "Total emails sent by the campaign.",+ "total_opened": "Total emails opened.",+ "total_clicked": "Total emails with a clicked link.",+ "total_replied": "Total leads that replied.",+ "open_rate": "Percentage of sent emails that were opened.",+ "click_rate": "Percentage of sent emails with a clicked link.",+ "reply_rate": "Percentage of sent emails that received a reply.",+ "bounce_rate": "Percentage of sent emails that bounced.",+ "unsubscribe_rate": "Percentage of leads that unsubscribed.",+ },+ },+ "email_accounts": {+ "description": "A sending email account connected to Smartlead, with SMTP/IMAP connection state, sending limits, and warmup status. Mailbox passwords are stripped before rows are stored.",+ "docs_url": "https://api.smartlead.ai/api-reference/email-accounts/get-all",+ "columns": {+ "id": "Unique email account identifier.",+ "from_name": "Display name for outgoing emails.",+ "from_email": "Email address the account sends from.",+ "username": "Email account username.",+ "type": "Account type: GMAIL, OUTLOOK, or SMTP.",+ "smtp_host": "SMTP server hostname.",+ "smtp_port": "SMTP server port.",+ "is_smtp_success": "Whether the SMTP connection is working.",+ "imap_host": "IMAP server hostname.",+ "imap_port": "IMAP server port.",+ "is_imap_success": "Whether the IMAP connection is working.",+ "message_per_day": "Maximum messages this account may send per day.",+ "daily_sent_count": "Messages sent today.",+ "warmup_details": "Warmup status and metrics: status, sent count, spam count, and reputation.",+ "client_id": "Associated client ID for agency accounts, null otherwise.",+ "created_at": "ISO 8601 timestamp when the account was added.",+ "updated_at": "ISO 8601 timestamp of the last modification.",+ },+ },+ "clients": {+ "description": "A whitelabel client sub-account under the main Smartlead account.",+ "docs_url": "https://api.smartlead.ai/api-reference/clients/get-all",+ "columns": {+ "id": "Unique client identifier.",+ "name": "Client name.",+ "email": "Client account email address.",+ "created_at": "ISO 8601 timestamp when the client was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/settings.pynew file mode 100644index 000000000000..a58e46006745--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/settings.py@@ -0,0 +1,132 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://server.smartlead.ai/api/v1"++# Leads and email accounts cap `limit` at 100. Statistics accepts up to 1000, but its rows carry+# full email subject/body HTML, so the shared 100 keeps page memory bounded.+PAGE_SIZE = 100++# Every endpoint syncs as full refresh. Smartlead documents server-side time filters on two list+# endpoints (`created_at_gt` on campaign leads, `sent_time_start_date` on campaign statistics),+# but neither filter has been verified against a live account and neither endpoint documents its+# sort order, so an ascending watermark cannot be trusted. Enable incremental only after a live+# smoke test proves the filter is honored and the response order is known.+++# Mutable by choice, not oversight: instances flow into `build_dependent_resource`'s+# `endpoint_configs: Mapping[str, FanoutEndpointLike]`, and mypy treats a frozen dataclass's+# fields as read-only, which is incompatible with that Protocol's plain (read-write) attributes.+@dataclass(frozen=False)+class SmartleadEndpointConfig:+ name: str+ # Path under /api/v1. The account-level list endpoints are documented with a trailing slash.+ path: str+ # "offset": offset/limit pagination terminated by a short page. "single": the endpoint returns+ # the whole collection (or one object) in a single response and takes no pagination params.+ pagination: Literal["offset", "single"] = "single"+ # Root key of the row list in the JSON body. None means the body is the row list itself.+ data_selector: Optional[str] = None+ # False only for endpoints whose body is a single JSON object (campaign analytics), which is+ # wrapped into a one-row page instead of being validated as a list.+ expects_list: bool = True+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field for datetime partitioning. Never an updated_at-style field.+ partition_key: Optional[str] = "created_at"+ # Response fields dropped before rows reach the warehouse. Smartlead returns connected+ # mailbox SMTP/IMAP passwords (base64-encoded) on email accounts; credentials must never+ # land in a synced table.+ redact_fields: tuple[str, ...] = ()+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # The cursor field the fan-out helper would bind a server filter to. Only read for fan-out+ # children, and only once an endpoint advertises incremental fields.+ default_incremental_field: Optional[str] = None+ # Set for per-campaign resources that hang off the account-level campaign list.+ fanout: Optional[DependentEndpointConfig] = None+ page_size: int = PAGE_SIZE+++def _campaign_fanout() -> DependentEndpointConfig:+ # Child rows don't consistently carry their campaign id, so inject the parent's `id` as+ # `campaign_id` on every child row; composite primary keys rely on it.+ return DependentEndpointConfig(+ parent_name="campaigns",+ resolve_param="campaign_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "campaign_id"},+ )+++SMARTLEAD_ENDPOINTS: dict[str, SmartleadEndpointConfig] = {+ # Returns the full campaign list as a bare array, newest first, with no pagination params.+ "campaigns": SmartleadEndpointConfig(+ name="campaigns",+ path="/campaigns/",+ ),+ # Bare array of sequence steps per campaign. The docs' JSON example shows a `data` envelope+ # but the same page states "Response Format: array"; the array shape matches the live API's+ # historical behavior. `data_selector_required` fails loud if the shape ever changes.+ "campaign_sequences": SmartleadEndpointConfig(+ name="campaign_sequences",+ path="/campaigns/{campaign_id}/sequences",+ primary_keys=["campaign_id", "id"],+ fanout=_campaign_fanout(),+ ),+ "campaign_leads": SmartleadEndpointConfig(+ name="campaign_leads",+ path="/campaigns/{campaign_id}/leads",+ pagination="offset",+ data_selector="data",+ # `campaign_lead_map_id` identifies the lead-to-campaign mapping row. Keep the campaign id+ # in the key anyway so a duplicate can never span campaigns.+ primary_keys=["campaign_id", "campaign_lead_map_id"],+ fanout=_campaign_fanout(),+ ),+ "campaign_statistics": SmartleadEndpointConfig(+ name="campaign_statistics",+ path="/campaigns/{campaign_id}/statistics",+ pagination="offset",+ data_selector="data",+ # `stats_id` identifies one sent email. The current docs list rows without it, but the+ # live API returns it; harmless if absent since this table only syncs as full refresh.+ primary_keys=["campaign_id", "stats_id"],+ # Statistics rows are send events; the send time never changes.+ partition_key="sent_time",+ fanout=_campaign_fanout(),+ ),+ # One aggregate metrics object per campaign. The row's identity is the injected campaign id+ # because the response body's own id field differs between docs and the live API.+ "campaign_analytics": SmartleadEndpointConfig(+ name="campaign_analytics",+ path="/campaigns/{campaign_id}/analytics",+ expects_list=False,+ primary_keys=["campaign_id"],+ partition_key=None,+ fanout=_campaign_fanout(),+ ),+ "email_accounts": SmartleadEndpointConfig(+ name="email_accounts",+ path="/email-accounts/",+ pagination="offset",+ redact_fields=("password", "imap_password"),+ ),+ # Whitelabel client sub-accounts. The docs' example shows an `{ok, data}` envelope, but the+ # live API has historically returned a bare array; `data_selector_required` fails loud+ # rather than syncing a garbage row if the envelope shape is what ships.+ "clients": SmartleadEndpointConfig(+ name="clients",+ path="/client/",+ ),+}++ENDPOINTS = tuple(SMARTLEAD_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in SMARTLEAD_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/smartlead.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/smartlead.pynew file mode 100644index 000000000000..296d7d8dd7d8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/smartlead.py@@ -0,0 +1,258 @@+from collections.abc import Iterable+from typing import Any, Optional, cast+from urllib.parse import urlencode++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.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ OffsetPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.settings import (+ BASE_URL,+ SMARTLEAD_ENDPOINTS,+ SmartleadEndpointConfig,+)+++@frozen+class SmartleadResumeConfig:+ # Top-level offset-paginated endpoints resume from the next offset. None means "start over".+ next_offset: int | None = None+ # Fan-out endpoints resume by parent: the campaign paths already fully synced, the campaign+ # in progress, and that campaign's paginator state — see+ # `common.rest_source.__init__._make_paginate_dependent_resource`.+ completed: list[str] | None = None+ current: str | None = None+ child_state: dict[str, Any] | None = None+++def _paginator(config: SmartleadEndpointConfig) -> BasePaginator:+ if config.pagination == "offset":+ # Smartlead reports totals as strings (e.g. `total_leads: "150"`), which the numeric+ # total check ignores, so the short-page fallback is what terminates pagination.+ return OffsetPaginator(limit=config.page_size, total_path=None)+ return SinglePagePaginator()+++def _client_config(api_key: str, paginator: BasePaginator) -> ClientConfig:+ return {+ "base_url": BASE_URL,+ "headers": {"Accept": "application/json"},+ # Smartlead's only auth method is the `api_key` query param. The framework auth config+ # redacts the key from logged URLs and captured samples.+ "auth": {"type": "api_key", "name": "api_key", "api_key": api_key, "location": "query"},+ "paginator": paginator,+ }+++def _endpoint_extra(config: SmartleadEndpointConfig) -> Endpoint:+ extra: Endpoint = {"paginator": _paginator(config)}+ if config.data_selector:+ extra["data_selector"] = config.data_selector+ if config.expects_list:+ # Fail loud on a response shape change instead of silently syncing 0 rows.+ extra["data_selector_required"] = True+ return extra+++def _redact_fields_mapper(fields: tuple[str, ...]):+ def _mapper(row: dict[str, Any]) -> dict[str, Any]:+ for field_name in fields:+ row.pop(field_name, None)+ return row++ return _mapper+++def _make_source_response(config: SmartleadEndpointConfig, items: Any, column_hints: Any = None) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ column_hints=column_hints,+ )+++def _top_level_source(+ config: SmartleadEndpointConfig,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[SmartleadResumeConfig],+ db_incremental_field_last_value: Optional[Any],+) -> SourceResponse:+ endpoint_config: Endpoint = {"path": config.path, "params": {}}+ endpoint_config.update(_endpoint_extra(config))++ resource: dict[str, Any] = {+ "name": endpoint,+ "endpoint": endpoint_config,+ }+ if config.redact_fields:+ resource["data_map"] = _redact_fields_mapper(config.redact_fields)++ rest_config: RESTAPIConfig = {+ "client": _client_config(api_key, _paginator(config)),+ "resource_defaults": {},+ "resources": [cast(Any, resource)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if config.pagination == "offset" and resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.next_offset:+ initial_paginator_state = {"offset": resume.next_offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only while more pages remain; save AFTER a page is yielded so a crash re-yields+ # the last page rather than skipping it. Single-page endpoints never produce state.+ if state and state.get("offset") is not None:+ resumable_source_manager.save_state(SmartleadResumeConfig(next_offset=int(state["offset"])))++ built = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return _make_source_response(config, lambda: built, column_hints=built.column_hints)+++def _fanout_source(+ config: SmartleadEndpointConfig,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[SmartleadResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ incremental_field: str | None,+) -> SourceResponse:+ assert config.fanout is not None+ parent_config = SMARTLEAD_ENDPOINTS[config.fanout.parent_name]++ initial_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and (resume.completed or resume.current):+ initial_state = {+ "completed": resume.completed or [],+ "current": resume.current,+ "child_state": resume.child_state,+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state is not None:+ resumable_source_manager.save_state(+ SmartleadResumeConfig(+ completed=state.get("completed"),+ current=state.get("current"),+ child_state=state.get("child_state"),+ )+ )++ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=SMARTLEAD_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=_client_config(api_key, _paginator(config)),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field=incremental_field,+ # The campaign parent list is unpaginated while children page with offset/limit, so+ # each side carries its own paginator instead of sharing the client's.+ parent_endpoint_extra=_endpoint_extra(parent_config),+ child_endpoint_extra=_endpoint_extra(config),+ # The parent takes no page-size param (unpaginated); the children's OffsetPaginator+ # injects `offset` and `limit` itself.+ page_size_param=None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ ),+ )++ return _make_source_response(config, lambda: dependent_resource)+++def smartlead_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[SmartleadResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = SMARTLEAD_ENDPOINTS[endpoint]++ if config.fanout is not None:+ return _fanout_source(+ config,+ api_key,+ endpoint,+ team_id,+ job_id,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ incremental_field,+ )++ return _top_level_source(+ config,+ api_key,+ endpoint,+ team_id,+ job_id,+ resumable_source_manager,+ db_incremental_field_last_value,+ )+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ """Probe the email accounts list with limit=1 to confirm the API key is genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error.+ """+ query = urlencode({"api_key": api_key, "offset": 0, "limit": 1})+ return validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,)),+ f"{BASE_URL}/email-accounts/?{query}",+ headers={"Accept": "application/json"},+ # The key rides in the query string; following a redirect would replay it to the+ # redirect target.+ allow_redirects=False,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/source.pyindex f07e53d5495d..bab5743121d2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/source.py@@ -1,16 +1,46 @@-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.smartlead import (SmartleadSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.smartlead import (+ SmartleadResumeConfig,+ smartlead_source,+ validate_credentials as validate_smartlead_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SmartleadSource(SimpleSource[SmartleadSourceConfig]):+class SmartleadSource(ResumableSource[SmartleadSourceConfig, SmartleadResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = "https://api.smartlead.ai"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SMARTLEAD@@ -21,7 +51,89 @@ class SmartleadSource(SimpleSource[SmartleadSourceConfig]):name=ExternalDataSourceType.SMARTLEAD,category=DataWarehouseSourceCategory.SALES,label="Smartlead",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Smartlead API key to pull your cold email campaigns, leads, statistics, email accounts, and clients into the PostHog Data warehouse.++Find or create your API key under **Settings → Smartlead API key** in your Smartlead account. The key has access to everything your account can see.""",iconPath="/static/services/smartlead.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/smartlead",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when the REST client calls+ # `raise_for_status()`. Retrying can never fix a credential problem, so fail the+ # sync. Match the stable status text, not the per-request path.+ "401 Client Error: Unauthorized": "Your Smartlead API key is invalid or has been revoked. Create a new key in your Smartlead settings, then reconnect.",+ "403 Client Error: Forbidden": "Your Smartlead API key does not have access to this data. Check the key in your Smartlead settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: SmartleadSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # Every INCREMENTAL_FIELDS entry is empty today (see settings.py for why), so every+ # endpoint comes back full refresh.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: SmartleadSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ ok, status_code = validate_smartlead_credentials(config.api_key)++ if ok:+ return True, None+ if status_code == 401:+ return False, "Invalid Smartlead API key"+ return False, "Could not connect to Smartlead with the provided API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SmartleadResumeConfig]:+ return ResumableSourceManager[SmartleadResumeConfig](inputs, SmartleadResumeConfig)++ def source_for_pipeline(+ self,+ config: SmartleadSourceConfig,+ resumable_source_manager: ResumableSourceManager[SmartleadResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return smartlead_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,+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/tests/test_smartlead.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/tests/test_smartlead.pynew file mode 100644index 000000000000..4c46a7f46403--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/tests/test_smartlead.py@@ -0,0 +1,276 @@+import json+from typing import Any++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.settings import PAGE_SIZE+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.smartlead import (+ SmartleadResumeConfig,+ smartlead_source,+ validate_credentials,+)++# RESTClient builds its session via make_tracked_session in the rest_client module.+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+# validate_credentials builds its own tracked session in the smartlead module.+SMARTLEAD_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.smartlead.make_tracked_session"+)+FANOUT_REST_RESOURCES_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+)+++def _response(body: Any) -> Response:+ resp = Response()+ resp.status_code = 200+ resp._content = json.dumps(body).encode()+ return resp+++def _make_manager(resume_state: SmartleadResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ """Wire a mock session and return a list that captures each request AT SEND TIME.++ ``request.params`` is a single dict mutated in place across pages, so inspecting it after the+ run shows only the final state — snapshot a copy when each request is prepared instead.+ """+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})+ return mock.MagicMock()++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):+ return smartlead_source(+ api_key="key",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,+ )+++def _rows(source_response) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _accounts(count: int, start: int = 0) -> list[dict[str, Any]]:+ return [{"id": start + i, "from_email": f"a{start + i}@example.com"} for i in range(count)]+++class TestSmartleadSource:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_offset_pagination_walks_until_short_page(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [_response(_accounts(PAGE_SIZE)), _response(_accounts(1, start=PAGE_SIZE))],+ )++ rows = _rows(_source("email_accounts", _make_manager()))++ assert len(rows) == PAGE_SIZE + 1+ assert session.send.call_count == 2+ assert snapshots[0]["url"] == "https://server.smartlead.ai/api/v1/email-accounts/"+ assert snapshots[0]["params"] == {"offset": 0, "limit": PAGE_SIZE}+ assert snapshots[1]["params"]["offset"] == PAGE_SIZE++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_auth_is_framework_api_key_query_param(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response(_accounts(1))])++ _rows(_source("email_accounts", _make_manager()))++ auth = snapshots[0]["auth"]+ assert isinstance(auth, APIKeyAuth)+ assert auth.name == "api_key"+ assert auth.location == "query"+ assert auth.api_key == "key"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_email_accounts_strip_mailbox_credentials(self, MockSession) -> None:+ # Smartlead returns the connected mailbox's SMTP/IMAP passwords (base64-encoded) on+ # this endpoint; syncing them would store live credentials in the warehouse.+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(+ [+ {+ "id": 1,+ "from_email": "[email protected]",+ "password": "c2VjcmV0",+ "imap_password": "c2VjcmV0",+ }+ ]+ )+ ],+ )++ rows = _rows(_source("email_accounts", _make_manager()))++ assert rows == [{"id": 1, "from_email": "[email protected]"}]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_campaigns_single_page_never_paginates(self, MockSession) -> None:+ # The campaign list is unpaginated. An offset paginator here would refetch the same full+ # array forever, because a full-length page never triggers the short-page stop.+ session = MockSession.return_value+ snapshots = _wire(session, [_response([{"id": i} for i in range(PAGE_SIZE * 2)])])++ rows = _rows(_source("campaigns", _make_manager()))++ assert len(rows) == PAGE_SIZE * 2+ assert session.send.call_count == 1+ assert snapshots[0]["url"] == "https://server.smartlead.ai/api/v1/campaigns/"+ assert "offset" not in snapshots[0]["params"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_enveloped_body_on_list_endpoint_fails_loud(self, MockSession) -> None:+ # The docs show an `{ok, data}` envelope for /client/ while the live API historically+ # returns a bare array. Whichever way the API answers, a non-list body must raise+ # instead of silently syncing a garbage row.+ session = MockSession.return_value+ _wire(session, [_response({"ok": True, "data": [{"id": 1}]})])++ with pytest.raises(ValueError, match="Required a list response body"):+ _rows(_source("clients", _make_manager()))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_resume_state_only_while_pages_remain(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(session, [_response(_accounts(PAGE_SIZE)), _response(_accounts(1, start=PAGE_SIZE))])++ manager = _make_manager()+ _rows(_source("email_accounts", manager))++ manager.save_state.assert_called_once()+ assert manager.save_state.call_args.args[0] == SmartleadResumeConfig(next_offset=PAGE_SIZE)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_offset(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(session, [_response(_accounts(1, start=PAGE_SIZE))])++ rows = _rows(_source("email_accounts", _make_manager(SmartleadResumeConfig(next_offset=PAGE_SIZE))))++ assert [r["id"] for r in rows] == [PAGE_SIZE]+ assert session.send.call_count == 1+ assert snapshots[0]["params"]["offset"] == PAGE_SIZE+++class TestSmartleadFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_leads_fan_out_paginates_per_campaign_and_injects_campaign_id(self, MockSession) -> None:+ session = MockSession.return_value+ snapshots = _wire(+ session,+ [+ _response([{"id": 11}, {"id": 22}]),+ _response(+ {"total_leads": str(PAGE_SIZE + 1), "data": [{"campaign_lead_map_id": i} for i in range(PAGE_SIZE)]}+ ),+ _response({"total_leads": str(PAGE_SIZE + 1), "data": [{"campaign_lead_map_id": PAGE_SIZE}]}),+ _response({"total_leads": "1", "data": [{"campaign_lead_map_id": 9000}]}),+ ],+ )++ rows = _rows(_source("campaign_leads", _make_manager()))++ # Parent listed once (no pagination), campaign 11 paged twice, campaign 22 once.+ assert session.send.call_count == 4+ assert snapshots[0]["url"].endswith("/campaigns/")+ assert "offset" not in snapshots[0]["params"]+ assert snapshots[1]["url"].endswith("/campaigns/11/leads")+ assert snapshots[1]["params"]["offset"] == 0+ assert snapshots[2]["params"]["offset"] == PAGE_SIZE+ assert snapshots[3]["url"].endswith("/campaigns/22/leads")+ assert snapshots[3]["params"]["offset"] == 0++ assert len(rows) == PAGE_SIZE + 2+ # Lead rows don't carry their campaign id; the fan-out injects it for the composite key.+ assert rows[0]["campaign_id"] == 11+ assert rows[-1]["campaign_id"] == 22++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_analytics_object_body_becomes_one_row_per_campaign(self, MockSession) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response([{"id": 11}]),+ _response({"campaign_name": "Q1", "total_sent": 10}),+ ],+ )++ rows = _rows(_source("campaign_analytics", _make_manager()))++ assert rows == [{"campaign_name": "Q1", "total_sent": 10, "campaign_id": 11}]++ @mock.patch(FANOUT_REST_RESOURCES_PATCH)+ def test_fan_out_resumes_completed_and_current_campaign(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ mock.MagicMock(name="campaigns"),+ mock.MagicMock(name="campaign_leads"),+ ]+ mock_rest_api_resources.return_value[0].name = "campaigns"+ mock_rest_api_resources.return_value[1].name = "campaign_leads"++ resume = SmartleadResumeConfig(+ completed=["/campaigns/11/leads"],+ current="/campaigns/22/leads",+ child_state={"offset": PAGE_SIZE},+ )+ _source("campaign_leads", _make_manager(resume))++ _, kwargs = mock_rest_api_resources.call_args+ assert kwargs["initial_paginator_state"] == {+ "completed": ["/campaigns/11/leads"],+ "current": "/campaigns/22/leads",+ "child_state": {"offset": PAGE_SIZE},+ }+++class TestValidateCredentials:+ @pytest.mark.parametrize("status_code, expected", [(200, (True, 200)), (401, (False, 401)), (403, (False, 403))])+ @mock.patch(SMARTLEAD_SESSION_PATCH)+ def test_status_mapping(self, mock_session, status_code, expected) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)+ assert validate_credentials("key") == expected++ @mock.patch(SMARTLEAD_SESSION_PATCH)+ def test_swallows_transport_errors(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = Exception("boom")+ assert validate_credentials("key") == (False, None)++ @mock.patch(SMARTLEAD_SESSION_PATCH)+ def test_probe_carries_key_in_query_and_never_follows_redirects(self, mock_session) -> None:+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)+ validate_credentials("key")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://server.smartlead.ai/api/v1/email-accounts/?api_key=key&offset=0&limit=1"+ # The key rides in the query string; following a redirect would replay it off-host.+ assert call.kwargs["allow_redirects"] is False+ # The tracked session must mask the key in logs and captured samples.+ assert mock_session.call_args.kwargs["redact_values"] == ("key",)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/tests/test_smartlead_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/tests/test_smartlead_source.pynew file mode 100644index 000000000000..1f7b41d366c2--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/smartlead/tests/test_smartlead_source.py@@ -0,0 +1,78 @@+import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.smartlead import (+ SmartleadSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.source import SmartleadSource++VALIDATE_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.smartlead.source.validate_smartlead_credentials"+)+++class TestSmartleadSource:+ def setup_method(self):+ self.source = SmartleadSource()+ self.team_id = 123+ self.config = SmartleadSourceConfig(api_key="key")++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://server.smartlead.ai/api/v1/campaigns/ | api error: Invalid API Key",+ "403 Client Error: Forbidden for url: https://server.smartlead.ai/api/v1/client/",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @pytest.mark.parametrize(+ "other_error",+ [+ "429 Client Error: Too Many Requests for url: https://server.smartlead.ai/api/v1/campaigns/",+ "500 Server Error: Internal Server Error for url: https://server.smartlead.ai/api/v1/campaigns/",+ "HTTPSConnectionPool(host='server.smartlead.ai', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_every_endpoint_is_full_refresh_only(self):+ # Smartlead's documented time filters (`created_at_gt`, `sent_time_start_date`) are+ # unverified against a live account and the list ordering is undocumented, so no schema+ # may advertise incremental sync until that changes (see settings.py).+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, 200), True, None),+ ((False, 401), False, "Invalid Smartlead API key"),+ ((False, 403), False, "Could not connect to Smartlead with the provided API key"),+ ((False, None), False, "Could not connect to Smartlead with the provided API key"),+ ],+ )+ @mock.patch(VALIDATE_PATCH)+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("key")