: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 leadfeeder import source (#67801)
Tom Owers1c75a3c2854e
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex db995f9af9f0..758974fb92f2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -183,6 +183,7 @@ the row lists both.| launchdarkly | HTTP | requests | ✅ || kustomer | HTTP | requests | ✅ || lattice | HTTP | requests | ✅ |+| leadfeeder | HTTP | requests | ✅ || lemlist | HTTP | requests | ✅ || lightspeed_retail | HTTP | requests | ✅ || linear | HTTP | requests | ✅ |@@ -487,7 +488,6 @@ doesn't conflict with concurrent PRs.- klaus- knock- kyve-- leadfeeder- leexi- lemon_squeezy- less_annoying_crmdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 66a96e902665..2b52b2a33d51 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1786,7 +1786,8 @@ class LaunchDarklySourceConfig(config.Config):@config.configclass LeadfeederSourceConfig(config.Config):- pass+ api_token: str+ start_date: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/canonical_descriptions.pynew file mode 100644index 000000000000..81bf43ef94c5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/canonical_descriptions.py@@ -0,0 +1,71 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the public legacy Leadfeeder (Dealfront) API reference+# (https://docs.leadfeeder.com/api/). Keyed by the endpoint names `get_schemas` returns.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "accounts": {+ "description": "Leadfeeder accounts (subscriptions) the API token can read.",+ "docs_url": "https://docs.leadfeeder.com/api/",+ "columns": {+ "id": "Unique identifier of the Leadfeeder account.",+ "type": "JSON:API resource type, always 'accounts'.",+ "name": "Human-readable name of the account.",+ },+ },+ "leads": {+ "description": "Identified companies that visited the tracked website, one row per (account, company).",+ "docs_url": "https://docs.leadfeeder.com/api/",+ "columns": {+ "id": "Unique identifier of the lead (company) within Leadfeeder.",+ "type": "JSON:API resource type, always 'leads'.",+ "account_id": "Identifier of the Leadfeeder account this lead belongs to.",+ "name": "Company name.",+ "industry": "Primary industry classification of the company.",+ "industries": "All industry classifications of the company.",+ "first_visit_date": "Date of the company's first recorded visit (yyyy-mm-dd).",+ "last_visit_date": "Date of the company's most recent visit (yyyy-mm-dd).",+ "status": "Lead status in Leadfeeder.",+ "website_url": "Company website URL.",+ "phone": "Company phone number.",+ "linkedin_url": "Company LinkedIn profile URL.",+ "twitter_handle": "Company Twitter/X handle.",+ "facebook_url": "Company Facebook page URL.",+ "employee_count": "Estimated number of employees.",+ "employees_range": "Estimated employee count as a range bucket.",+ "crm_lead_id": "Identifier of the linked lead in a connected CRM.",+ "crm_organization_id": "Identifier of the linked organization in a connected CRM.",+ "tags": "Tags applied to the lead.",+ "logo_url": "URL of the company logo.",+ "assignee": "User the lead is assigned to.",+ "business_id": "Company business/registration identifier.",+ "revenue": "Estimated company revenue.",+ "quality": "Leadfeeder-computed lead quality score.",+ "visits": "Number of visits attributed to the company in the queried window.",+ },+ },+ "visits": {+ "description": "Individual website visits across the account, one row per visit.",+ "docs_url": "https://docs.leadfeeder.com/api/",+ "columns": {+ "id": "Unique identifier of the visit.",+ "type": "JSON:API resource type, always 'visits'.",+ "account_id": "Identifier of the Leadfeeder account this visit belongs to.",+ "lead_id": "Identifier of the lead (company) the visit is attributed to.",+ "started_at": "Timestamp the visit started, ISO 8601, rounded to minutes.",+ "visit_length": "Duration of the visit in seconds.",+ "source": "Traffic source of the visit.",+ "medium": "Traffic medium of the visit.",+ "campaign": "Marketing campaign associated with the visit.",+ "referring_url": "URL that referred the visit.",+ "landing_page_path": "Path of the first page viewed in the visit.",+ "visit_route": "Sequence of pages viewed during the visit.",+ "page_depth": "Number of pages viewed during the visit.",+ "keyword": "Search keyword associated with the visit, when available.",+ "query_term": "Site search query term, when available.",+ "country_code": "ISO country code inferred for the visit.",+ "device_type": "Device category used for the visit.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.pynew file mode 100644index 000000000000..f10e8dbecdb0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.py@@ -0,0 +1,365 @@+"""Transport for the Leadfeeder (Dealfront) data warehouse source.++Targets the legacy Leadfeeder API at https://api.leadfeeder.com, authenticated with the+`Authorization: Token token=<token>` header. This generation exposes the well-documented+accounts / leads / visits streams with JSON:API page-number pagination and a server-side+`start_date`/`end_date` date-range filter — the same shape Airbyte's connector targets.++Leadfeeder also ships a newer API-first generation (`X-Api-Key` auth on `/v1/*`, Companies &+Contacts, web-visits/search). Its stream shapes could not be verified against the live API without+credentials, so this source deliberately implements the stable legacy generation and ships as an+unreleased alpha. Endpoint/field names below come from the public legacy API reference; if the live+API differs they may need adjustment.+"""++import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.settings import (+ LEADFEEDER_ENDPOINTS,+ LeadfeederEndpointConfig,+)++LEADFEEDER_BASE_URL = "https://api.leadfeeder.com"+PAGE_SIZE = 100 # JSON:API page[size] max is 100 (default 10)+DEFAULT_LOOKBACK_DAYS = 365 # First-sync window when the user leaves start_date blank+# Backstop against a paginator that never returns a null `links.next`. The API terminates naturally,+# so hitting this signals a bug or an API change rather than normal operation.+MAX_PAGES_PER_ACCOUNT = 10_000+++class LeadfeederRetryableError(Exception):+ pass+++class LeadfeederResumeConfig:+ # The account currently being paginated (fan-out endpoints). None for the top-level `accounts`+ # endpoint. A stable account id — not a positional index — so accounts added/removed between a+ # crash and the retry can't resume us into the wrong account.+ account_id: str | None = None+ # Full next-page URL (from the API's `links.next`) to resume from within the current account.+ # None means "start this account/endpoint from its first page".+ next_url: str | None = None+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Token token={api_token}",+ "Accept": "application/json",+ # Leadfeeder asks integrations to identify themselves via User-Agent.+ "User-Agent": "PostHog",+ }+++def _build_url(path: str, params: dict[str, Any]) -> str:+ """Build an absolute URL with a query string.++ Leadfeeder's JSON:API pagination uses bracketed keys (`page[number]`, `page[size]`). All keys and+ values here are internally constructed and ASCII-safe (numbers and yyyy-mm-dd dates), so they're+ joined literally rather than percent-encoded — the API expects the literal brackets.+ """+ base = f"{LEADFEEDER_BASE_URL}{path}"+ if not params:+ return base+ query = "&".join(f"{key}={value}" for key, value in params.items())+ return f"{base}?{query}"+++def _parse_response(response: "requests.Response", url: str, logger: FilteringBoundLogger) -> dict:+ """Classify a response and return its JSON body, raising on error.++ Kept separate from the retry wrapper so the retryable-vs-terminal classification can be tested+ without driving tenacity's backoff sleeps.+ """+ # Leadfeeder returns 429 when the ~100 req/min budget is exceeded; retry those and any 5xx.+ if response.status_code == 429 or response.status_code >= 500:+ raise LeadfeederRetryableError(f"Leadfeeder API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # 404 is expected and handled during fan-out (an account deleted mid-sync).+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Leadfeeder API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++@retry(+ retry=retry_if_exception_type(+ (+ LeadfeederRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ 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) -> dict:+ response = session.get(url, headers=headers, timeout=60)+ return _parse_response(response, url, logger)+++def _flatten_item(item: dict[str, Any], account_id: str | None) -> dict[str, Any]:+ """Flatten a JSON:API resource object into a single flat row.++ JSON:API items look like `{"id", "type", "attributes": {...}}`; we lift `attributes` to the root+ and keep `id`/`type`. Fan-out rows also carry the parent `account_id` so the composite primary key+ stays unique across every account.+ """+ # `id` is the primary key, so read it directly: a malformed item without one should fail loudly+ # rather than seed a row under a `None` key that later merges multi-match or duplicate.+ row: dict[str, Any] = {"id": item["id"], "type": item.get("type")}+ attributes = item.get("attributes")+ if isinstance(attributes, dict):+ row.update(attributes)+ if account_id is not None:+ row["account_id"] = account_id+ return row+++def _to_date_str(value: Any) -> str:+ """Coerce a date / datetime / ISO string incremental value to a yyyy-mm-dd string.++ Leadfeeder's start_date/end_date filter is day-granular, so a datetime cursor (e.g. a visit's+ `started_at`) is floored to its date. Re-querying from the floored day re-reads that whole day,+ which merge dedupes on the primary key — so the incremental sync is self-healing even though the+ filter is coarser than the cursor.+ """+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ return str(value)[:10]+++def _compute_date_range(+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ start_date_config: str,+) -> tuple[str, str]:+ """Resolve the required (start_date, end_date) window for a leads/visits request."""+ end = datetime.now(UTC).date()+ if should_use_incremental_field and db_incremental_field_last_value:+ start = _to_date_str(db_incremental_field_last_value)+ elif start_date_config:+ start = _to_date_str(start_date_config)+ else:+ start = (end - timedelta(days=DEFAULT_LOOKBACK_DAYS)).isoformat()+ return start, end.isoformat()+++def _make_session(api_token: str) -> requests.Session:+ """Tracked session for Leadfeeder requests.++ `redact_values=(api_token,)` masks the token wherever it lands in logged URLs or captured HTTP+ samples — the `Authorization: Token token=...` header name isn't on the generic denylist.+ `allow_redirects=False` keeps the credentialed request pinned to `api.leadfeeder.com` so a+ redirect can't resend the token to another host.+ """+ return make_tracked_session(redact_values=(api_token,), allow_redirects=False)+++def validate_credentials(api_token: str) -> bool:+ url = f"{LEADFEEDER_BASE_URL}/accounts"+ try:+ response = _make_session(api_token).get(url, headers=_get_headers(api_token), timeout=10)+ return response.status_code == 200+ except Exception:+ return False+++def _iter_account_ids(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[str]:+ """Page through /accounts and yield each account id, following `links.next`."""+ url = _build_url("/accounts", {"page[number]": 1, "page[size]": PAGE_SIZE})+ pages = 0+ while True:+ data = _fetch_page(session, url, headers, logger)+ for item in data.get("data", []):+ account_id = item.get("id")+ if account_id is not None:+ yield str(account_id)++ next_url = data.get("links", {}).get("next")+ pages += 1+ if not next_url or pages >= MAX_PAGES_PER_ACCOUNT:+ break+ url = next_url+++def _iter_top_level_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: LeadfeederEndpointConfig,+ resumable_source_manager: ResumableSourceManager[LeadfeederResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Paginate a top-level endpoint (e.g. /accounts), yielding one list of rows per page."""+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = resume.next_url+ logger.debug(f"Leadfeeder: resuming {config.name} from {url}")+ else:+ url = _build_url(config.path, {"page[number]": 1, "page[size]": PAGE_SIZE})++ pages = 0+ while True:+ data = _fetch_page(session, url, headers, logger)+ rows = [_flatten_item(item, account_id=None) for item in data.get("data", [])]+ next_url = data.get("links", {}).get("next")++ if rows:+ yield rows+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes) rather than+ # skipping it. Only persist when more pages remain.+ if next_url:+ resumable_source_manager.save_state(LeadfeederResumeConfig(next_url=next_url))++ pages += 1+ if not next_url:+ break+ if pages >= MAX_PAGES_PER_ACCOUNT:+ logger.warning(f"Leadfeeder: hit page cap ({MAX_PAGES_PER_ACCOUNT}) for {config.name}")+ break+ url = next_url+++def _iter_fan_out_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: LeadfeederEndpointConfig,+ resumable_source_manager: ResumableSourceManager[LeadfeederResumeConfig],+ start_date: str,+ end_date: str,+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every account, paginating the child endpoint per account.++ Rows carry their parent `account_id`. Resume state bookmarks the current account id plus the+ next-page URL within it, so a crash resumes into the same account and page rather than restarting.+ """+ account_ids = list(_iter_account_ids(session, headers, logger))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = account_ids+ resume_url: str | None = None+ if resume is not None and resume.account_id is not None and resume.account_id in account_ids:+ remaining = account_ids[account_ids.index(resume.account_id) :]+ resume_url = resume.next_url+ logger.debug(f"Leadfeeder: resuming {config.name} from account={resume.account_id}, url={resume_url}")++ date_params = {"start_date": start_date, "end_date": end_date, "page[size]": PAGE_SIZE}++ for index, account_id in enumerate(remaining):+ path = config.path.format(account_id=account_id)+ url = resume_url or _build_url(path, {"page[number]": 1, **date_params})+ resume_url = None # only the resumed-into account uses the saved URL; the rest start fresh++ try:+ pages = 0+ while True:+ data = _fetch_page(session, url, headers, logger)+ rows = [_flatten_item(item, account_id=account_id) for item in data.get("data", [])]+ next_url = data.get("links", {}).get("next")++ if rows:+ yield rows+ if next_url:+ resumable_source_manager.save_state(+ LeadfeederResumeConfig(account_id=account_id, next_url=next_url)+ )++ pages += 1+ if not next_url:+ break+ if pages >= MAX_PAGES_PER_ACCOUNT:+ logger.warning(+ f"Leadfeeder: hit page cap ({MAX_PAGES_PER_ACCOUNT}) for {config.name}, account={account_id}"+ )+ break+ url = next_url+ except requests.HTTPError as exc:+ # An account revoked between enumeration and this fetch 404s. Skip it rather than failing+ # the whole sync. Any other HTTP error is re-raised.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Leadfeeder: account {account_id} not found while fetching {config.name}, skipping")+ else:+ raise++ # Advance the bookmark to the next account so a crash between accounts resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(LeadfeederResumeConfig(account_id=remaining[index + 1], next_url=None))+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LeadfeederResumeConfig],+ start_date_config: str = "",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ config = LEADFEEDER_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ # One session reused across every page (and, for fan-out, every account) so urllib3 keeps the+ # connection alive instead of re-handshaking per request.+ session = _make_session(api_token)++ if config.fan_out_over_accounts:+ start_date, end_date = _compute_date_range(+ should_use_incremental_field, db_incremental_field_last_value, start_date_config+ )+ yield from _iter_fan_out_rows(session, headers, logger, config, resumable_source_manager, start_date, end_date)+ return++ yield from _iter_top_level_rows(session, headers, logger, config, resumable_source_manager)+++def leadfeeder_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LeadfeederResumeConfig],+ start_date_config: str = "",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = LEADFEEDER_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ start_date_config=start_date_config,+ 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="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/settings.pynew file mode 100644index 000000000000..60c07b05e135--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/settings.py@@ -0,0 +1,98 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# All Leadfeeder (Dealfront) endpoints implemented here target the legacy Leadfeeder API+# (https://api.leadfeeder.com), authenticated with `Authorization: Token token=<token>`. This is the+# generation Airbyte's connector targets and the one with a documented, stable JSON:API shape+# (accounts / leads / visits, page-number pagination, start_date/end_date filtering). A newer+# API-first generation (X-Api-Key on /v1/*) also exists but its stream shapes could not be verified+# against the live API here — see the module docstring in leadfeeder.py.+++def _date_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.Date,+ "field": name,+ "field_type": IncrementalFieldType.Date,+ }+++def _datetime_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++@dataclass+class LeadfeederEndpointConfig:+ name: str+ # Path relative to the API base. Fan-out endpoints carry an `{account_id}` placeholder resolved+ # per account at request time.+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable datetime/date field rows are partitioned by. Never an updated_at / last_seen style field+ # that shifts over time — see the skill's partitioning guidance.+ partition_key: Optional[str] = None+ # When True the endpoint is queried once per Leadfeeder account (the account id is injected into+ # `path`). Fan-out rows aggregate across every account, so the account id is part of the primary+ # key to keep it unique table-wide.+ fan_out_over_accounts: bool = False+ # When True the endpoint honours the server-side `start_date`/`end_date` date-range filter, which+ # makes it genuinely incremental. Endpoints without a server filter are full refresh only.+ supports_date_filter: bool = False+ should_sync_default: bool = True+++LEADFEEDER_ENDPOINTS: dict[str, LeadfeederEndpointConfig] = {+ # The set of Leadfeeder accounts (subscriptions) the token can read. A small dimension table with+ # no server-side time filter, so full refresh only. It also seeds the account ids the leads/visits+ # fan-out iterates over.+ "accounts": LeadfeederEndpointConfig(+ name="accounts",+ path="/accounts",+ primary_keys=["id"],+ ),+ # Identified companies that visited the tracked site, one row per (account, company). The+ # `/accounts/{account_id}/leads` endpoint requires a start_date/end_date range and filters on it+ # server-side, so it's incremental. Partition by `first_visit_date` (stable) and track the+ # advancing `last_visit_date` as the incremental cursor.+ "leads": LeadfeederEndpointConfig(+ name="leads",+ path="/accounts/{account_id}/leads",+ primary_keys=["account_id", "id"],+ partition_key="first_visit_date",+ fan_out_over_accounts=True,+ supports_date_filter=True,+ incremental_fields=[+ _date_field("last_visit_date"),+ _date_field("first_visit_date"),+ ],+ ),+ # Individual website visits across the account. `/accounts/{account_id}/visits` also takes a+ # required start_date/end_date range filtered server-side. Visits are immutable events, so+ # partition by and track `started_at`.+ "visits": LeadfeederEndpointConfig(+ name="visits",+ path="/accounts/{account_id}/visits",+ primary_keys=["account_id", "id"],+ partition_key="started_at",+ fan_out_over_accounts=True,+ supports_date_filter=True,+ incremental_fields=[+ _datetime_field("started_at"),+ ],+ ),+}++ENDPOINTS = tuple(LEADFEEDER_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LEADFEEDER_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/source.pyindex f074acf1f136..fc6f5cfcb0cf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LeadfeederSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder import (+ LeadfeederResumeConfig,+ leadfeeder_source,+ validate_credentials as validate_leadfeeder_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ LEADFEEDER_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LeadfeederSource(SimpleSource[LeadfeederSourceConfig]):+class LeadfeederSource(ResumableSource[LeadfeederSourceConfig, LeadfeederResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LEADFEEDER@@ -22,9 +46,112 @@ class LeadfeederSource(SimpleSource[LeadfeederSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.LEADFEEDER,- category=DataWarehouseSourceCategory.SALES,+ category=DataWarehouseSourceCategory.CRM,label="Leadfeeder",- iconPath="/static/services/leadfeeder.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ keywords=["dealfront"],+ caption="""Enter your Leadfeeder (Dealfront) API token to pull your website visitor and lead data into the PostHog Data warehouse.++Generate a token in your [Leadfeeder API settings](https://app.leadfeeder.com/settings/api). This uses the legacy Leadfeeder API (`Authorization: Token`), which syncs the **Accounts**, **Leads**, and **Visits** tables.++Optionally set a **Start date** to bound the initial sync — leave it blank to pull the last year of leads and visits.""",+ iconPath="/static/services/leadfeeder.png",+ docsUrl="https://posthog.com/docs/cdp/sources/leadfeeder",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2024-01-01",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # A missing/invalid Leadfeeder token surfaces as an HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never fix a credential problem. Match the stable+ # status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.leadfeeder.com": "Your Leadfeeder API token is invalid or has been revoked. Generate a new token in your Leadfeeder API settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.leadfeeder.com": "Your Leadfeeder API token is missing or does not have access to this data. Check the token in your Leadfeeder API settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: LeadfeederSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = LEADFEEDER_ENDPOINTS[endpoint]+ # Only endpoints with a server-side start_date/end_date filter are genuinely incremental.+ has_incremental = endpoint_config.supports_date_filter+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.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: LeadfeederSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_leadfeeder_credentials(config.api_token):+ return True, None++ return (+ False,+ "Unable to verify your Leadfeeder API token. Check that the token is correct and that Leadfeeder is reachable.",+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LeadfeederResumeConfig]:+ return ResumableSourceManager[LeadfeederResumeConfig](inputs, LeadfeederResumeConfig)++ def source_for_pipeline(+ self,+ config: LeadfeederSourceConfig,+ resumable_source_manager: ResumableSourceManager[LeadfeederResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return leadfeeder_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ start_date_config=config.start_date or "",+ 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/leadfeeder/tests/test_leadfeeder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.pynew file mode 100644index 000000000000..87d2d39b6d48--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder.py@@ -0,0 +1,288 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder import leadfeeder+from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder import (+ LEADFEEDER_BASE_URL,+ LeadfeederResumeConfig,+ LeadfeederRetryableError,+ _build_url,+ _compute_date_range,+ _flatten_item,+ _to_date_str,+ get_rows,+ leadfeeder_source,+ validate_credentials,+)+++class _FakeResponse:+ def __init__(self, status_code: int = 200, json_data: Any = None, text: str = ""):+ self.status_code = status_code+ self._json_data = json_data+ self.text = text++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ def json(self) -> Any:+ return self._json_data++ def raise_for_status(self) -> None:+ if not self.ok:+ raise requests.HTTPError(f"{self.status_code} Client Error", response=self) # type: ignore[arg-type]+++class _FakeSession:+ """Returns queued responses in order; records the URLs requested."""++ def __init__(self, responses: list[_FakeResponse]):+ self._responses = list(responses)+ self.requested_urls: list[str] = []++ def get(self, url: str, **kwargs: Any) -> _FakeResponse:+ self.requested_urls.append(url)+ return self._responses.pop(0)+++def _manager(can_resume: bool = False, state: LeadfeederResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = can_resume+ manager.load_state.return_value = state+ return manager+++def _run(+ endpoint: str, responses: list[_FakeResponse], manager: mock.MagicMock, **kwargs: Any+) -> tuple[list[list[dict]], _FakeSession]:+ session = _FakeSession(responses)+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder.make_tracked_session",+ return_value=session,+ ):+ return list(get_rows("token", endpoint, mock.MagicMock(), manager, **kwargs)), session+++def _item(id_: str, type_: str, **attributes: Any) -> dict[str, Any]:+ return {"id": id_, "type": type_, "attributes": attributes}+++class TestFlattenItem:+ def test_lifts_attributes_and_keeps_id_type(self) -> None:+ row = _flatten_item(_item("1", "leads", name="Acme", last_visit_date="2024-06-01"), account_id=None)+ assert row == {"id": "1", "type": "leads", "name": "Acme", "last_visit_date": "2024-06-01"}++ def test_injects_account_id_for_fan_out(self) -> None:+ row = _flatten_item(_item("9", "visits", started_at="2024-06-01T10:00:00Z"), account_id="42")+ assert row["account_id"] == "42"+ assert row["id"] == "9"++ def test_handles_missing_attributes(self) -> None:+ assert _flatten_item({"id": "1", "type": "accounts"}, account_id=None) == {"id": "1", "type": "accounts"}++ def test_missing_id_fails_loudly(self) -> None:+ # `id` is the primary key: a missing one must raise rather than seed a row under a None key.+ with pytest.raises(KeyError):+ _flatten_item({"type": "leads", "attributes": {"name": "Acme"}}, account_id="1")+++class TestToDateStr:+ @parameterized.expand(+ [+ (datetime(2024, 6, 1, 15, 30, tzinfo=UTC), "2024-06-01"),+ (date(2024, 6, 1), "2024-06-01"),+ ("2024-06-01T09:00:00Z", "2024-06-01"),+ ("2024-06-01", "2024-06-01"),+ ]+ )+ def test_coerces_to_day_granular_string(self, value: Any, expected: str) -> None:+ assert _to_date_str(value) == expected+++class TestComputeDateRange:+ @freeze_time("2026-07-02")+ def test_incremental_uses_watermark_as_start(self) -> None:+ start, end = _compute_date_range(True, date(2024, 5, 1), "2020-01-01")+ assert start == "2024-05-01"+ assert end == "2026-07-02"++ @freeze_time("2026-07-02")+ def test_incremental_floors_datetime_watermark_to_day(self) -> None:+ start, _ = _compute_date_range(True, datetime(2024, 5, 1, 23, 59, tzinfo=UTC), "")+ assert start == "2024-05-01"++ @freeze_time("2026-07-02")+ def test_full_refresh_uses_config_start_date(self) -> None:+ start, end = _compute_date_range(False, None, "2023-01-01")+ assert start == "2023-01-01"+ assert end == "2026-07-02"++ @freeze_time("2026-07-02")+ def test_full_refresh_defaults_to_lookback_window(self) -> None:+ start, _ = _compute_date_range(False, None, "")+ assert start == "2025-07-02"+++class TestParseResponse:+ @parameterized.expand([(429,), (500,), (503,)])+ def test_retryable_statuses_raise_retryable_error(self, status: int) -> None:+ with pytest.raises(LeadfeederRetryableError):+ leadfeeder._parse_response(_FakeResponse(status_code=status), "http://x", mock.MagicMock()) # type: ignore[arg-type]++ @parameterized.expand([(401,), (403,), (404,)])+ def test_client_errors_raise_http_error(self, status: int) -> None:+ with pytest.raises(requests.HTTPError):+ leadfeeder._parse_response(_FakeResponse(status_code=status, text="nope"), "http://x", mock.MagicMock()) # type: ignore[arg-type]++ def test_ok_returns_json_body(self) -> None:+ body = {"data": [{"id": "1"}]}+ assert leadfeeder._parse_response(_FakeResponse(json_data=body), "http://x", mock.MagicMock()) == body # type: ignore[arg-type]+++class TestValidateCredentials:+ @parameterized.expand([("valid", 200, True), ("unauthorized", 401, False), ("server_error", 500, False)])+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder.make_tracked_session"+ )+ def test_status_mapping(self, _name: str, status: int, expected: bool, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _FakeResponse(status_code=status)+ assert validate_credentials("token") is expected++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder.make_tracked_session"+ )+ def test_exception_returns_false(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("boom")+ assert validate_credentials("token") is False++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder.make_tracked_session"+ )+ def test_sends_token_auth_header(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.return_value = _FakeResponse(status_code=200)+ validate_credentials("secret")+ assert mock_session.return_value.get.call_args.kwargs["headers"]["Authorization"] == "Token token=secret"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder.make_tracked_session"+ )+ def test_session_redacts_token_and_blocks_redirects(self, mock_session: mock.MagicMock) -> None:+ # The token rides in a custom `Authorization: Token token=...` header the denylist can't see,+ # so it must be registered for value-based redaction; redirects must not be followed or the+ # credentialed request could resend the token off-origin.+ mock_session.return_value.get.return_value = _FakeResponse(status_code=200)+ validate_credentials("secret")+ assert mock_session.call_args.kwargs["redact_values"] == ("secret",)+ assert mock_session.call_args.kwargs["allow_redirects"] is False+++class TestTopLevelPagination:+ def test_follows_next_link_and_saves_state_after_batch(self) -> None:+ page2_url = f"{LEADFEEDER_BASE_URL}/accounts?page[number]=2&page[size]=100"+ responses = [+ _FakeResponse(json_data={"data": [_item("1", "accounts", name="A")], "links": {"next": page2_url}}),+ _FakeResponse(json_data={"data": [_item("2", "accounts", name="B")], "links": {}}),+ ]+ manager = _manager()+ batches, session = _run("accounts", responses, manager)++ assert batches == [+ [{"id": "1", "type": "accounts", "name": "A"}],+ [{"id": "2", "type": "accounts", "name": "B"}],+ ]+ # State is saved once, pointing at the next page, only after the first batch is yielded.+ manager.save_state.assert_called_once_with(LeadfeederResumeConfig(next_url=page2_url))+ # The second page is fetched from the URL the API handed back.+ assert session.requested_urls[1] == page2_url++ def test_resumes_from_saved_next_url(self) -> None:+ resume_url = f"{LEADFEEDER_BASE_URL}/accounts?page[number]=5&page[size]=100"+ manager = _manager(can_resume=True, state=LeadfeederResumeConfig(next_url=resume_url))+ responses = [_FakeResponse(json_data={"data": [_item("7", "accounts")], "links": {}})]+ _batches, session = _run("accounts", responses, manager)+ assert session.requested_urls[0] == resume_url++ def test_empty_page_yields_nothing(self) -> None:+ batches, _ = _run("accounts", [_FakeResponse(json_data={"data": [], "links": {}})], _manager())+ assert batches == []+++class TestFanOut:+ def _accounts_response(self, *ids: str) -> _FakeResponse:+ return _FakeResponse(json_data={"data": [_item(i, "accounts") for i in ids], "links": {}})++ def test_iterates_every_account_and_injects_account_id(self) -> None:+ responses = [+ self._accounts_response("1", "2"),+ _FakeResponse(json_data={"data": [_item("100", "leads", name="Acme")], "links": {}}),+ _FakeResponse(json_data={"data": [_item("200", "leads", name="Globex")], "links": {}}),+ ]+ batches, session = _run("leads", responses, _manager())++ assert batches == [+ [{"id": "100", "type": "leads", "name": "Acme", "account_id": "1"}],+ [{"id": "200", "type": "leads", "name": "Globex", "account_id": "2"}],+ ]+ # The lead request carries the server-side date-range filter.+ leads_url = next(u for u in session.requested_urls if "/accounts/1/leads" in u)+ assert "start_date=" in leads_url and "end_date=" in leads_url++ def test_resume_skips_already_processed_accounts(self) -> None:+ manager = _manager(can_resume=True, state=LeadfeederResumeConfig(account_id="2", next_url=None))+ responses = [+ self._accounts_response("1", "2"),+ _FakeResponse(json_data={"data": [_item("200", "leads")], "links": {}}),+ ]+ batches, session = _run("leads", responses, manager)++ assert batches == [[{"id": "200", "type": "leads", "account_id": "2"}]]+ assert not any("/accounts/1/leads" in u for u in session.requested_urls)++ def test_unknown_account_in_saved_state_restarts_from_first(self) -> None:+ # An account deleted between runs must not wedge the sync — fall back to the full list.+ manager = _manager(can_resume=True, state=LeadfeederResumeConfig(account_id="999", next_url=None))+ responses = [+ self._accounts_response("1"),+ _FakeResponse(json_data={"data": [_item("100", "leads")], "links": {}}),+ ]+ batches, _ = _run("leads", responses, manager)+ assert batches == [[{"id": "100", "type": "leads", "account_id": "1"}]]+++class TestBuildUrl:+ def test_no_params(self) -> None:+ assert _build_url("/accounts", {}) == f"{LEADFEEDER_BASE_URL}/accounts"++ def test_keeps_literal_brackets(self) -> None:+ url = _build_url("/accounts", {"page[number]": 1, "page[size]": 100})+ assert url == f"{LEADFEEDER_BASE_URL}/accounts?page[number]=1&page[size]=100"+++class TestSourceResponse:+ def test_accounts_is_full_refresh_without_partitioning(self) -> None:+ response = leadfeeder_source("token", "accounts", mock.MagicMock(), _manager())+ assert response.name == "accounts"+ assert response.primary_keys == ["id"]+ assert response.partition_mode is None++ @parameterized.expand(+ [+ ("leads", ["account_id", "id"], "first_visit_date"),+ ("visits", ["account_id", "id"], "started_at"),+ ]+ )+ def test_fan_out_endpoints_have_composite_key_and_partition(+ self, endpoint: str, primary_keys: list[str], partition_key: str+ ) -> None:+ response = leadfeeder_source("token", endpoint, mock.MagicMock(), _manager())+ assert response.primary_keys == primary_keys+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [partition_key]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder_source.pynew file mode 100644index 000000000000..acb0e725dfda--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/tests/test_leadfeeder_source.py@@ -0,0 +1,155 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LeadfeederSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder import (+ LeadfeederResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.source import LeadfeederSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestLeadfeederSource:+ def setup_method(self) -> None:+ self.source = LeadfeederSource()+ self.team_id = 123+ self.config = LeadfeederSourceConfig(api_token="token", start_date="2024-01-01")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.LEADFEEDER++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Leadfeeder"+ assert config.label == "Leadfeeder"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Kept unreleased until the alpha has been exercised end to end against the live API.+ assert config.unreleasedSource is True+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/leadfeeder"+ assert [f.name for f in config.fields] == ["api_token", "start_date"]++ def test_api_token_field_is_secret_password(self) -> None:+ token_field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldInputConfig) and f.name == "api_token"+ )+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O, so public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ @parameterized.expand(+ [+ "401 Client Error: Unauthorized for url: https://api.leadfeeder.com/accounts",+ "403 Client Error: Forbidden for url: https://api.leadfeeder.com/accounts/1/leads",+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ "429 Client Error: Too Many Requests for url: https://api.leadfeeder.com/accounts/1/visits",+ "500 Server Error for url: https://api.leadfeeder.com/accounts",+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_get_schemas_marks_only_date_filtered_endpoints_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert set(schemas) == set(ENDPOINTS)+ # Accounts has no server-side date filter -> full refresh only.+ assert schemas["accounts"].supports_incremental is False+ assert schemas["accounts"].supports_append is False+ # Leads and visits filter server-side on start_date/end_date -> incremental.+ for name in ("leads", "visits"):+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["leads"])+ assert [s.name for s in schemas] == ["leads"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @parameterized.expand(+ [+ (True, True, None),+ (+ False,+ False,+ "Unable to verify your Leadfeeder API token. Check that the token is correct and that Leadfeeder is reachable.",+ ),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.source.validate_leadfeeder_credentials"+ )+ def test_validate_credentials(+ self, mock_return: bool, expected_valid: bool, expected_message: str | None, mock_validate: mock.MagicMock+ ) -> None:+ 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("token")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LeadfeederResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.source.leadfeeder_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "leads"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-06-01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_token"] == "token"+ assert kwargs["endpoint"] == "leads"+ assert kwargs["start_date_config"] == "2024-01-01"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == "2024-06-01"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.source.leadfeeder_source")+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self, mock_source: mock.MagicMock) -> None:+ # A stale watermark must not leak into a full-refresh run.+ config = LeadfeederSourceConfig(api_token="token")+ inputs = mock.MagicMock()+ inputs.schema_name = "accounts"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-06-01"++ self.source.source_for_pipeline(config, mock.MagicMock(), inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["db_incremental_field_last_value"] is None+ assert kwargs["start_date_config"] == ""++ def test_canonical_descriptions_cover_key_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions) == set(ENDPOINTS)+ assert "last_visit_date" in descriptions["leads"]["columns"]+ assert "started_at" in descriptions["visits"]["columns"]++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)