Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(warehouse): add lemlist contacts, campaign leads, reports and sequences (#114505)

Tom Owers464fa0b4c39d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index b785725d0b45..673daea8bbcb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -5069,10 +5069,10 @@ Today (5): `activities`, `campaigns`, `team`, `team_senders`, `unsubscribes`
Diffed against: <https://developer.lemlist.com/api-reference/openapi/v2.json>
-- [ ] `GET /campaigns/{campaignId}/leads/ (and GET /leads)` — the prospect records a campaign is actually working - the fact table the synced activities point at (high)
-- [ ] `GET /contacts` — unified contact records with custom variables; the identity table for joining activities to people (high)
-- [ ] `GET /campaigns/reports and GET /v2/campaigns/{campaignId}/stats` — headline campaign performance metrics (sends, opens, replies, interested) without re-aggregating raw activities (high)
-- [ ] `GET /campaigns/{campaignId}/sequences` — lookup resolving the sequence and step ids carried on every activity row (high)
+- [x] `GET /campaigns/{campaignId}/leads/ (and GET /leads)` — the prospect records a campaign is actually working - the fact table the synced activities point at (high)
+- [x] `GET /contacts` — unified contact records with custom variables; the identity table for joining activities to people (high)
+- [x] `GET /campaigns/reports and GET /v2/campaigns/{campaignId}/stats` — headline campaign performance metrics (sends, opens, replies, interested) without re-aggregating raw activities (high)
+- [x] `GET /campaigns/{campaignId}/sequences` — lookup resolving the sequence and step ids carried on every activity row (high)
- [ ] `GET /campaigns/{campaignId}/statutes` — per-lead campaign state (paused, finished, interested) - the transition status behind funnel reporting (medium)
- [ ] `GET /companies (and GET /companies/{companyId}/notes)` — company records for account-level outreach reporting (medium)
- [ ] `GET /inbox and GET /inbox/{contactId}` — conversations and messages, the reply side of outreach that activities only summarize (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/canonical_descriptions.py
index 025ae749129e..cd317ebacc2b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/canonical_descriptions.py
@@ -65,4 +65,74 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"scope": "Scope of the unsubscribe (campaign, team or global).",
},
},
+ "contacts": {
+ "description": "Contacts in your lemlist team: the people record that campaign leads point at through contactId.",
+ "docs_url": "https://developer.lemlist.com/api-reference/endpoints/contacts/get-many-contacts",
+ "columns": {
+ "_id": "Unique contact identifier.",
+ "teamId": "ID of the team that owns the contact.",
+ "fullName": "Full name of the contact.",
+ "email": "Email address of the contact.",
+ "firstName": "First name of the contact.",
+ "lastName": "Last name of the contact.",
+ "phone": "Phone number of the contact.",
+ "jobTitle": "Job title of the contact.",
+ "linkedinUrl": "LinkedIn profile URL of the contact.",
+ "ownerId": "User ID of the contact owner.",
+ "companyId": "ID of the company the contact is attached to.",
+ "createdAt": "When the contact was created.",
+ "createdBy": "User ID that created the contact.",
+ "unsubscribed": "Whether the contact has unsubscribed.",
+ "campaignCount": "Number of campaigns the contact is in.",
+ },
+ },
+ "campaign_leads": {
+ "description": "Leads in each campaign, with their latest state. A lead is a contact enrolled in one campaign.",
+ "docs_url": "https://developer.lemlist.com/api-reference/endpoints/campaigns/export-campaign-leads-v2",
+ "columns": {
+ "_id": "Unique lead identifier within the campaign.",
+ "campaignId": "ID of the campaign the lead belongs to.",
+ "email": "Email address of the lead.",
+ "emailStatus": "Email deliverability status (deliverable, risky, undeliverable).",
+ "firstName": "First name of the lead.",
+ "lastName": "Last name of the lead.",
+ "companyName": "Company name of the lead.",
+ "companyDomain": "Company domain of the lead.",
+ "jobTitle": "Job title of the lead.",
+ "linkedinUrl": "LinkedIn profile URL of the lead.",
+ "lastState": "Latest state the lead reached in the campaign (e.g. contacted, interested).",
+ "status": "Status of the lead in the campaign.",
+ },
+ },
+ "campaign_reports": {
+ "description": "All-time headline statistics per campaign: lead counts, emails and LinkedIn messages sent, opened, clicked and replied, and interest.",
+ "docs_url": "https://developer.lemlist.com/api-reference/endpoints/campaigns/get-campaign-reports",
+ "columns": {
+ "_id": "Campaign ID.",
+ "name": "Campaign name.",
+ "createdAt": "When the campaign was created.",
+ "state": "Campaign state (running, paused, etc.).",
+ "status": "Campaign status (draft, ended, etc.).",
+ "totalCount": "Total number of leads in the campaign.",
+ "inSequenceLeadCount": "Number of leads in the sequence.",
+ "emailsSent": "Number of emails sent.",
+ "emailsOpened": "Number of emails opened.",
+ "emailsClicked": "Number of emails with links clicked.",
+ "emailsReplied": "Number of emails replied to.",
+ "emailsUnsubscribed": "Number of leads that unsubscribed by email.",
+ "linkedinSent": "Number of LinkedIn messages sent.",
+ "linkedinReplied": "Number of LinkedIn messages replied to.",
+ "interested": "Number of leads marked as interested.",
+ "notInterested": "Number of leads marked as not interested.",
+ },
+ },
+ "campaign_sequences": {
+ "description": "Sequences of each campaign with their ordered steps. Resolves the sequenceId and stepId on activities.",
+ "docs_url": "https://developer.lemlist.com/api-reference/endpoints/sequences/get-campaign-sequences",
+ "columns": {
+ "_id": "Unique sequence identifier.",
+ "campaignId": "ID of the campaign the sequence belongs to.",
+ "steps": "Ordered steps of the sequence, each with _id, type, delay, index, subject and message.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/lemlist.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/lemlist.py
index 164830d6536b..3583b564b363 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/lemlist.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/lemlist.py
@@ -1,4 +1,5 @@
import dataclasses
+from collections.abc import Iterable
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional, cast
@@ -8,15 +9,25 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
rest_api_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import HttpBasicAuth
+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 (
OffsetPaginator,
SinglePagePaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+)
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.lemlist.settings import LEMLIST_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.lemlist.settings import (
+ LEMLIST_ENDPOINTS,
+ LemlistEndpointConfig,
+)
LEMLIST_BASE_URL = "https://api.lemlist.com/api"
# lemlist caps list pages at 100 rows and rate-limits to 20 requests / 2s per API key.
@@ -69,6 +80,74 @@ def _clamp_future_value_to_now(value: Any) -> Any:
return value
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": LEMLIST_BASE_URL,
+ # lemlist uses HTTP Basic auth with an empty username and the API key as the password.
+ # Supplied via the framework auth config so the key is redacted from logs and errors.
+ "auth": {"type": "http_basic", "username": "", "password": api_key},
+ }
+
+
+def _request_params(config: LemlistEndpointConfig, api_version: str) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.requires_version_v2 or (config.version_v2_enriches and api_version == LEMLIST_API_VERSION_V2):
+ params["version"] = LEMLIST_API_VERSION_V2
+ if config.request_sort_by:
+ params["sortBy"] = config.request_sort_by
+ if config.request_sort_order:
+ params["sortOrder"] = config.request_sort_order
+ return params
+
+
+def _campaign_fanout_source(
+ api_key: str,
+ endpoint: str,
+ config: LemlistEndpointConfig,
+ team_id: int,
+ job_id: str,
+ api_version: str,
+) -> SourceResponse:
+ assert config.fanout is not None
+ parent_config = LEMLIST_ENDPOINTS[config.fanout.parent_name]
+ fanout = dataclasses.replace(config.fanout, parent_params=_request_params(parent_config, api_version))
+
+ child_endpoint_extra: Endpoint = {"paginator": SinglePagePaginator()}
+ if config.data_selector:
+ child_endpoint_extra["data_selector"] = config.data_selector
+
+ resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=LEMLIST_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ # None of the per-campaign endpoints has a server-side time filter.
+ db_incremental_field_last_value=None,
+ # The parent's OffsetPaginator sends `limit`; the child endpoints take no page size.
+ page_size_param=None,
+ parent_endpoint_extra={"paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None)},
+ child_endpoint_extra=child_endpoint_extra,
+ ),
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ 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,
+ sort_mode=config.sort_mode,
+ )
+
+
def lemlist_source(
api_key: str,
endpoint: str,
@@ -80,14 +159,10 @@ def lemlist_source(
db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = LEMLIST_ENDPOINTS[endpoint]
+ if config.fanout is not None:
+ return _campaign_fanout_source(api_key, endpoint, config, team_id, job_id, api_version)
- params: dict[str, Any] = {}
- if config.requires_version_v2 or (config.version_v2_enriches and api_version == LEMLIST_API_VERSION_V2):
- params["version"] = LEMLIST_API_VERSION_V2
- if config.request_sort_by:
- params["sortBy"] = config.request_sort_by
- if config.request_sort_order:
- params["sortOrder"] = config.request_sort_order
+ params = _request_params(config, api_version)
# lemlist has no top-level `total`; the OffsetPaginator terminates on a short/empty page.
# Non-paginated endpoints (team, team/senders) return their whole result in one response.
@@ -96,6 +171,8 @@ def lemlist_source(
"params": params,
"paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None) if config.paginate else SinglePagePaginator(),
}
+ if config.data_selector:
+ endpoint_config["data_selector"] = config.data_selector
use_incremental = config.supports_incremental and should_use_incremental_field
if use_incremental:
@@ -113,12 +190,7 @@ def lemlist_source(
}
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": LEMLIST_BASE_URL,
- # lemlist uses HTTP Basic auth with an empty username and the API key as the password.
- # Supplied via the framework auth config so the key is redacted from logs and errors.
- "auth": {"type": "http_basic", "username": "", "password": api_key},
- },
+ "client": _client_config(api_key),
"resources": [
cast(
EndpointResource,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/settings.py
index 72f99f927e7a..b08445c4acfc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/settings.py
@@ -3,6 +3,9 @@ from typing import Optional
from posthog.dataclasses import frozen
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
@@ -36,6 +39,13 @@ class LemlistEndpointConfig:
# Bound the first incremental sync so we don't pull the entire activity history at once.
default_lookback_days: Optional[int] = None
should_sync_default: bool = True
+ # JSONPath to the row list when the response wraps it (e.g. /contacts returns {"data": [...]}).
+ data_selector: Optional[str] = None
+ # Per-campaign child endpoints fan out over /campaigns; their rows carry the parent id.
+ fanout: Optional[DependentEndpointConfig] = None
+ # Read by the shared fan-out helper; lemlist list pages hold at most 100 rows.
+ page_size: int = 100
+ default_incremental_field: Optional[str] = None
def _datetime_incremental_field(name: str) -> IncrementalField:
@@ -47,6 +57,22 @@ def _datetime_incremental_field(name: str) -> IncrementalField:
}
+def _campaign_fanout(
+ include_campaign_id: bool, child_params: Optional[dict[str, str]] = None
+) -> DependentEndpointConfig:
+ return DependentEndpointConfig(
+ parent_name="campaigns",
+ resolve_param="campaignId",
+ resolve_field="_id",
+ include_from_parent=["_id"] if include_campaign_id else [],
+ parent_field_renames={"_id": "campaignId"} if include_campaign_id else {},
+ child_params=child_params or {},
+ # A campaign deleted between the listing and the child fetch 404s; skip it rather than
+ # failing the sync with the "no user for this API key" 404 message.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ )
+
+
LEMLIST_ENDPOINTS: dict[str, LemlistEndpointConfig] = {
"campaigns": LemlistEndpointConfig(
name="campaigns",
@@ -88,6 +114,42 @@ LEMLIST_ENDPOINTS: dict[str, LemlistEndpointConfig] = {
name="unsubscribes",
path="/unsubscribes",
),
+ # Without a filter /contacts lists every contact in a {data, total, limit, offset} envelope. It
+ # exposes no sort or date filter, so it's full refresh only.
+ "contacts": LemlistEndpointConfig(
+ name="contacts",
+ path="/contacts",
+ data_selector="data",
+ partition_key="createdAt",
+ ),
+ # GET /campaigns/{id}/leads/ caps a response at 500 leads with no offset param, so the JSON
+ # export is the only way to read every lead of a campaign. Lead ids are scoped to their
+ # campaign, so the key carries the campaign id.
+ "campaign_leads": LemlistEndpointConfig(
+ name="campaign_leads",
+ path="/v2/campaigns/{campaignId}/export/leads",
+ paginate=False,
+ primary_keys=["campaignId", "_id"],
+ fanout=_campaign_fanout(include_campaign_id=True, child_params={"state": "all", "format": "json"}),
+ ),
+ # All-time headline stats per campaign; each report row's `_id` is the campaign id.
+ "campaign_reports": LemlistEndpointConfig(
+ name="campaign_reports",
+ path="/campaigns/reports?campaignIds={campaignId}",
+ paginate=False,
+ partition_key="createdAt",
+ fanout=_campaign_fanout(include_campaign_id=False),
+ ),
+ # The response is an object keyed by sequence id (condition branches are their own sequences),
+ # so `$.*` turns its values into one row per sequence, each with its ordered `steps`.
+ "campaign_sequences": LemlistEndpointConfig(
+ name="campaign_sequences",
+ path="/campaigns/{campaignId}/sequences",
+ paginate=False,
+ data_selector="$.*",
+ primary_keys=["campaignId", "_id"],
+ fanout=_campaign_fanout(include_campaign_id=True),
+ ),
}
ENDPOINTS = tuple(LEMLIST_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/tests/test_lemlist.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/tests/test_lemlist.py
index 4ca48ebe0cf6..22ef25fbc0ef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/tests/test_lemlist.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lemlist/tests/test_lemlist.py
@@ -47,7 +47,7 @@ def _make_manager(resume_state: LemlistResumeConfig | None = None) -> mock.Magic
return manager
-def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+def _wire(session: mock.MagicMock, responses: list[Response], urls: list[str] | None = None) -> list[dict[str, Any]]:
"""Wire a mock session and capture each request's params AT SEND TIME.
``request.params`` is a single dict mutated in place across pages, so inspecting it after the run
@@ -58,6 +58,8 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
def _prepare(request: Any) -> mock.MagicMock:
param_snapshots.append(dict(request.params or {}))
+ if urls is not None:
+ urls.append(request.url)
return mock.MagicMock()
session.prepare_request.side_effect = _prepare
@@ -167,15 +169,21 @@ class TestValidateCredentials:
class TestPagination:
+ @parameterized.expand(
+ [
+ ("bare_list", "campaigns", lambda rows: rows),
+ ("data_envelope", "contacts", lambda rows: {"data": rows, "total": PAGE_SIZE + 1}),
+ ]
+ )
@mock.patch(CLIENT_SESSION_PATCH)
- def test_paginates_until_short_page(self, MockSession) -> None:
+ def test_paginates_until_short_page(self, _name: str, endpoint: str, wrap, MockSession) -> None:
session = MockSession.return_value
- full_page = [{"_id": f"cam_{i}"} for i in range(PAGE_SIZE)]
- params = _wire(session, [_response(full_page), _response([{"_id": "cam_last"}])])
+ full_page = [{"_id": f"row_{i}"} for i in range(PAGE_SIZE)]
+ params = _wire(session, [_response(wrap(full_page)), _response(wrap([{"_id": "row_last"}]))])
manager = _make_manager()
- rows = _rows(_source("campaigns", manager))
+ rows = _rows(_source(endpoint, manager))
assert len(rows) == PAGE_SIZE + 1
- assert rows[-1] == {"_id": "cam_last"}
+ assert rows[-1] == {"_id": "row_last"}
assert params[0]["offset"] == 0
assert params[1]["offset"] == PAGE_SIZE
# State is saved once, after the first full page, pointing at the next offset.
@@ -192,6 +200,65 @@ class TestPagination:
assert params[0]["offset"] == PAGE_SIZE
+class TestCampaignFanout:
+ @parameterized.expand(
+ [
+ (
+ "leads_export",
+ "campaign_leads",
+ [{"_id": "lea_1", "email": "[email protected]"}],
+ "/v2/campaigns/cam_1/export/leads",
+ {"state": "all", "format": "json"},
+ [{"_id": "lea_1", "email": "[email protected]", "campaignId": "cam_1"}],
+ ),
+ (
+ "reports_bound_by_query",
+ "campaign_reports",
+ [{"_id": "cam_1", "emailsSent": 3}],
+ "/campaigns/reports?campaignIds=cam_1",
+ {},
+ [{"_id": "cam_1", "emailsSent": 3}],
+ ),
+ (
+ "sequences_keyed_object",
+ "campaign_sequences",
+ {"seq_1": {"_id": "seq_1", "steps": []}, "seq_2": {"_id": "seq_2", "steps": [{"_id": "stp_1"}]}},
+ "/campaigns/cam_1/sequences",
+ {},
+ [
+ {"_id": "seq_1", "steps": [], "campaignId": "cam_1"},
+ {"_id": "seq_2", "steps": [{"_id": "stp_1"}], "campaignId": "cam_1"},
+ ],
+ ),
+ ]
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_child_rows_per_campaign(
+ self,
+ _name: str,
+ endpoint: str,
+ child_payload: Any,
+ child_path: str,
+ child_params: dict[str, Any],
+ expected_rows: list[dict[str, Any]],
+ MockSession,
+ ) -> None:
+ session = MockSession.return_value
+ urls: list[str] = []
+ params = _wire(session, [_response([{"_id": "cam_1"}]), _response(child_payload)], urls)
+ rows = _rows(_source(endpoint))
+ assert rows == expected_rows
+ assert params[0] == {
+ "version": "v2",
+ "sortBy": "createdAt",
+ "sortOrder": "asc",
+ "offset": 0,
+ "limit": PAGE_SIZE,
+ }
+ assert urls[1].endswith(child_path)
+ assert params[1] == child_params
+
+
class TestRetryClassification:
@parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
@mock.patch(TENACITY_SLEEP_PATCH)