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_sources): support Leadfeeder API version 2026-08-07 (#80107)

Tom Owersd36223236db8
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index 8489d74fa4dd..1dd4ca9fc655 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -93,6 +93,7 @@ Add it when any of these hold:
- When the new version has no equivalent for an old endpoint (a dropped collection, not a rename), keep that table only on the versions that serve it and let the table set differ by version — never map it to a guessed path just to keep the sets equal, since docs are the sole source of truth and an unverified path makes a new source surface a table that 404s at sync time.
- A source with no dispatch may currently read its version from a constant on a shared model (e.g. the OAuth `Integration` model) that also drives version-independent flows like OAuth token minting. Repoint only the sync request path onto the resolved pin; leave that constant, since bumping it changes those other flows' version with a blast radius beyond this source.
- The opposite holds when the new version is a genuinely different vendor product rather than a renamed collection (the old and new labels serve different endpoints and tables): give the new version its own disjoint table set, don't force the old names onto it. That divergence is safe only because sources are never repinned — so a 2.5→3.0-style move is lossy, and its migration is documented-not-scripted, exactly like a rename that changes primary keys.
+- The shared REST framework only binds a resolved parent field into a child resource's URL **path**, not its query string (`_bind_path_params` raises "Resolve query params not supported yet"). If a new version scopes a fan-out child by a query param where the old version used a path segment, the dependent-resource `{"type": "resolve"}` machinery can't express it — iterate the parent ids explicitly in the source and bake each id into the child's params (or POST body) instead.
## Self-improvement
diff --git a/products/warehouse_sources/backend/migrations/0131_pin_leadfeeder_null_api_version_to_v1.py b/products/warehouse_sources/backend/migrations/0131_pin_leadfeeder_null_api_version_to_v1.py
new file mode 100644
index 000000000000..d64f92f52df5
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0131_pin_leadfeeder_null_api_version_to_v1.py
@@ -0,0 +1,37 @@
+from django.db import migrations
+
+# Leadfeeder's default vendor API version flips to "2026-08-07" (the unified Dealfront API) in the
+# same change that adds this migration. Existing Leadfeeder rows were pinned "v1" by migration 0075,
+# but a row created via a direct-ORM path that bypasses creation-time stamping could still have a
+# NULL `api_version`, and a NULL pin resolves to `default_version` — so it would silently follow the
+# flip to the unified API. The unified API needs a different credential (an X-Api-Key generated in
+# the Dealfront platform, which cannot be derived from a legacy Token) and a different request layer,
+# so an unpinned legacy source moved to it would break. Pin any such rows back to "v1" so the flip
+# only affects newly created sources.
+#
+# This does NOT repin legacy "v1" customers to the unified API: that migration is not safe to script
+# (the unified credential can't be derived from the legacy one, and the deprecation carries no sunset
+# date), so it is documented as a manual path in the PR.
+LEADFEEDER_SOURCE_TYPE = "Leadfeeder"
+LEADFEEDER_V1 = "v1"
+
+
+def pin_null_leadfeeder_rows_to_v1(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # The isnull guard keeps it idempotent (safe under retries) and never overwrites a concrete pin.
+ ExternalDataSource.objects.filter(source_type=LEADFEEDER_SOURCE_TYPE, api_version__isnull=True).update(
+ api_version=LEADFEEDER_V1
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources", "0130_repin_loop_returns_api_version"),
+ ]
+
+ operations = [
+ # Reverse is a no-op: after this runs, the pinned rows are indistinguishable from natively
+ # created v1 sources, so nulling "v1" pins would also destroy legitimate creation-time stamps.
+ migrations.RunPython(pin_null_leadfeeder_rows_to_v1, migrations.RunPython.noop, elidable=True),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 5d3f748c1542..f721b6eb2cb9 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0130_repin_loop_returns_api_version
+0131_pin_leadfeeder_null_api_version_to_v1
diff --git a/products/warehouse_sources/backend/migrations/test/test_migration_0131.py b/products/warehouse_sources/backend/migrations/test/test_migration_0131.py
new file mode 100644
index 000000000000..c5b44b1a4fcc
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/test/test_migration_0131.py
@@ -0,0 +1,59 @@
+import uuid
+import importlib
+
+import pytest
+
+from django.apps import apps
+
+from products.warehouse_sources.backend.facade.models import ExternalDataSource
+
+migration_module = importlib.import_module(
+ "products.warehouse_sources.backend.migrations.0131_pin_leadfeeder_null_api_version_to_v1"
+)
+pin_null_leadfeeder_rows_to_v1 = migration_module.pin_null_leadfeeder_rows_to_v1
+
+
+def source_factory(team):
+ def _create(source_type, api_version=None):
+ return ExternalDataSource.objects.create(
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ destination_id=str(uuid.uuid4()),
+ team=team,
+ status="running",
+ source_type=source_type,
+ api_version=api_version,
+ job_inputs={},
+ )
+
+ return _create
+
+
+class TestPinLeadfeederNullApiVersion:
+ def test_pins_only_null_leadfeeder_rows(self, source_factory):
+ unpinned = source_factory("Leadfeeder", api_version=None)
+ pinned_unified = source_factory("Leadfeeder", api_version="2026-08-07")
+ other_source = source_factory("Stripe", api_version=None)
+
+ pin_null_leadfeeder_rows_to_v1(apps, None)
+
+ unpinned.refresh_from_db()
+ pinned_unified.refresh_from_db()
+ other_source.refresh_from_db()
+ assert unpinned.api_version == "v1"
+ # An existing concrete pin (e.g. a source already moved to the unified API) must never be
+ # overwritten.
+ assert pinned_unified.api_version == "2026-08-07"
+ # Non-Leadfeeder sources are untouched.
+ assert other_source.api_version is None
+
+ def test_is_idempotent(self, source_factory):
+ source = source_factory("Leadfeeder", api_version=None)
+
+ pin_null_leadfeeder_rows_to_v1(apps, None)
+ pin_null_leadfeeder_rows_to_v1(apps, None)
+
+ source.refresh_from_db()
+ assert source.api_version == "v1"
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.py
index b580dfa622fb..a64c02a022f5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.py
@@ -1,19 +1,26 @@
"""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.
+The source implements two vendor API generations, both served from https://api.leadfeeder.com, and
+dispatches between them on the resolved API-version pin:
+
+- LEADFEEDER_API_LEGACY ("v1") — the legacy API, `Authorization: Token token=<token>`, JSON:API
+ page-number pagination (`page[number]`) with a `links.next` cursor, account-scoped
+ `/accounts/{id}/leads|visits` paths and a server-side `start_date`/`end_date` filter. The shape
+ Airbyte's connector targets and the label existing source rows are pinned to. The vendor has
+ deprecated it (maintenance-only, no new tokens issued) but still serves it, with no announced sunset.
+
+- LEADFEEDER_API_2026_08_07 — the unified Dealfront API, `X-Api-Key` on `/v1/*`, page-number
+ pagination via `page[num]` with a `meta.page_count` stop. The only generation new customers can
+ obtain credentials for, so it is the default for newly created sources. Its request layer (auth,
+ base paths, method, pagination) is dispatched here; row shapes reuse the version-independent
+ JSON:API flatten. Both come from the public OpenAPI spec (info.version 2026-08-07, marked
+ "work in progress") and warrant live verification before the source leaves alpha.
"""
import dataclasses
+from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
+from functools import partial
from typing import Any, Optional
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -24,10 +31,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
JSONResponsePaginator,
+ PageNumberPaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
+ Endpoint,
EndpointResource,
IncrementalConfig,
)
@@ -35,6 +44,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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.leadfeeder.settings import (
+ LEADFEEDER_API_2026_08_07,
+ LEADFEEDER_API_LEGACY,
LEADFEEDER_ENDPOINTS,
LeadfeederEndpointConfig,
)
@@ -166,6 +177,169 @@ def _base_params() -> dict[str, Any]:
return {"page[number]": 1, "page[size]": PAGE_SIZE}
+# --- Unified Dealfront API (X-Api-Key on /v1/*) --------------------------------------------------
+
+
+def _unified_headers(api_key: str) -> dict[str, str]:
+ return {"X-Api-Key": api_key, "Accept": "application/json", "User-Agent": "PostHog"}
+
+
+def _unified_base_params() -> dict[str, Any]:
+ # The unified API paginates by page number under `page[num]`; the paginator advances page[num]
+ # and stops at the last page reported in `meta.page_count`.
+ return {"page[size]": PAGE_SIZE}
+
+
+def _unified_client_config(api_key: str) -> ClientConfig:
+ # Auth via the framework api_key config so the key is redacted from any raised error; only the
+ # non-secret Accept/User-Agent headers are set on the client. Pin the request to the base host
+ # (allowed_hosts=[]) and disable redirects so the credentialed request can't be replayed off-origin.
+ return {
+ "base_url": LEADFEEDER_BASE_URL,
+ "auth": {
+ "type": "api_key",
+ "api_key": api_key,
+ "name": "X-Api-Key",
+ "location": "header",
+ },
+ "headers": {"Accept": "application/json", "User-Agent": "PostHog"},
+ "paginator": PageNumberPaginator(base_page=1, page_param="page[num]", total_path="meta.page_count"),
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ }
+
+
+def _unified_single_resource(
+ client: ClientConfig,
+ name: str,
+ endpoint: Endpoint,
+ team_id: int,
+ job_id: str,
+ data_map: Any,
+) -> Resource:
+ rest_config: RESTAPIConfig = {
+ "client": client,
+ "resources": [{"name": name, "endpoint": endpoint, "data_map": data_map}],
+ }
+ return rest_api_resource(rest_config, team_id, job_id, None)
+
+
+def _unified_accounts_endpoint() -> Endpoint:
+ # /v1/accounts returns its whole result set in one unpaginated, non-empty response with no
+ # `meta.page_count` field. The client-level PageNumberPaginator's total-pages stop check silently
+ # no-ops when that field is absent (it falls through to "has next page"), and `stop_after_empty_page`
+ # never fires either since the page is never empty — so without this override, a sync would keep
+ # requesting page[num]=2, 3, ... forever. Override with a page-number paginator capped at one page
+ # via `maximum_page`: it still requests `page[num]=1` like every other unified endpoint (so a vendor
+ # response that *does* start paginating accounts one day is requested consistently), but the
+ # `maximum_page=1` cap makes it stop after that one request no matter what the body contains —
+ # accounts is a small dimension table (see LEADFEEDER_ENDPOINTS), so a single page is authoritative.
+ accounts_config = LEADFEEDER_ENDPOINTS[_ACCOUNTS_RESOURCE]
+ return {
+ "path": accounts_config.unified_path,
+ "params": _unified_base_params(),
+ "data_selector": "data",
+ "paginator": PageNumberPaginator(base_page=1, page_param="page[num]", maximum_page=1),
+ }
+
+
+def _unified_account_ids(client: ClientConfig, team_id: int, job_id: str) -> Iterator[str]:
+ resource = _unified_single_resource(
+ client,
+ _ACCOUNTS_RESOURCE,
+ _unified_accounts_endpoint(),
+ team_id,
+ job_id,
+ _flatten_top_level,
+ )
+ for page in resource:
+ for row in page:
+ account_id = row.get("id")
+ if account_id is not None:
+ yield str(account_id)
+
+
+def _unified_leadfeeder_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ start_date_config: str = "",
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = LEADFEEDER_ENDPOINTS[endpoint]
+ client = _unified_client_config(api_key)
+
+ if not config.fan_out_over_accounts:
+ # Accounts needs its own bounded paginator (see _unified_accounts_endpoint); other non-fan-out
+ # endpoints, if any are added later, keep the client-level page_count-driven paginator.
+ single_endpoint: Endpoint = (
+ _unified_accounts_endpoint()
+ if endpoint == _ACCOUNTS_RESOURCE
+ else {"path": config.unified_path, "params": _unified_base_params(), "data_selector": "data"}
+ )
+ resource = _unified_single_resource(
+ client,
+ endpoint,
+ single_endpoint,
+ team_id,
+ job_id,
+ _flatten_top_level,
+ )
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+ # The unified fan-out endpoints take `account_id` as a query param, which the shared REST
+ # framework can't resolve from a parent resource (it only binds resolved params into the path),
+ # so iterate accounts explicitly and sync each account's window with the id baked in. The date
+ # range is computed from the incremental watermark (if any) or the configured start date;
+ # re-reading the floored day is self-healing since merge dedupes on the primary key.
+ start = (
+ _to_date_str(db_incremental_field_last_value)
+ if db_incremental_field_last_value is not None
+ else _default_start_date(start_date_config)
+ )
+ end = datetime.now(UTC).date().isoformat()
+
+ def _fanned() -> Iterator[list[dict[str, Any]]]:
+ for account_id in _unified_account_ids(client, team_id, job_id):
+ child_params: dict[str, Any] = {**_unified_base_params(), "account_id": account_id}
+ child_endpoint: Endpoint = {
+ "path": config.unified_path,
+ "params": child_params,
+ "data_selector": "data",
+ }
+ if config.unified_method == "POST":
+ # Web visits are a POST search whose date window lives in the body, not the query string.
+ child_endpoint["method"] = "POST"
+ child_endpoint["json"] = {"start_date": start, "end_date": end}
+ else:
+ child_params["start_date"] = start
+ child_params["end_date"] = end
+ yield from _unified_single_resource(
+ client, endpoint, child_endpoint, team_id, job_id, partial(_flatten_item, account_id=account_id)
+ )
+
+ # Partition only on a field confirmed present in the unified schema (visits' `started_at`). The
+ # visitor-companies rows carry no confirmed top-level date, so leads sync unpartitioned here.
+ partition_key = config.partition_key if endpoint == "visits" else None
+ return SourceResponse(
+ name=endpoint,
+ items=_fanned,
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if partition_key else None,
+ partition_format="month" if partition_key else None,
+ partition_keys=[partition_key] if partition_key else None,
+ )
+
+
def leadfeeder_source(
api_token: str,
endpoint: str,
@@ -176,7 +350,18 @@ def leadfeeder_source(
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
incremental_field: str | None = None,
+ api_version: str = LEADFEEDER_API_LEGACY,
) -> SourceResponse:
+ if api_version == LEADFEEDER_API_2026_08_07:
+ return _unified_leadfeeder_source(
+ api_key=api_token,
+ endpoint=endpoint,
+ team_id=team_id,
+ job_id=job_id,
+ start_date_config=start_date_config,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
config = LEADFEEDER_ENDPOINTS[endpoint]
fan_out = config.fan_out_over_accounts
@@ -271,12 +456,20 @@ def leadfeeder_source(
)
-def validate_credentials(api_token: str) -> bool:
- # The token rides in a custom `Authorization: Token token=...` header the denylist can't see, so
- # register it for value-based redaction; block redirects so the probe can't resend it off-origin.
+def validate_credentials(api_token: str, api_version: str = LEADFEEDER_API_LEGACY) -> bool:
+ # Probe the accounts list under the pinned generation: the legacy API takes an
+ # `Authorization: Token token=...` header, the unified API an `X-Api-Key` header on `/v1/accounts`.
+ # Both credentials ride in headers the denylist can't see, so register the value for redaction and
+ # block redirects so the probe can't resend it off-origin.
+ if api_version == LEADFEEDER_API_2026_08_07:
+ url = f"{LEADFEEDER_BASE_URL}/v1/accounts"
+ headers = _unified_headers(api_token)
+ else:
+ url = f"{LEADFEEDER_BASE_URL}/accounts"
+ headers = _get_headers(api_token)
ok, _status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_token,), allow_redirects=False),
- f"{LEADFEEDER_BASE_URL}/accounts",
- headers=_get_headers(api_token),
+ url,
+ headers=headers,
)
return ok
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.py
index 60c07b05e135..c7b4db44a3a0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/settings.py
@@ -3,12 +3,28 @@ 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.
+# Leadfeeder (Dealfront) exposes two vendor API generations, both served from
+# https://api.leadfeeder.com. The source dispatches between them on the resolved API-version pin
+# (see leadfeeder.py for the request layer):
+#
+# LEADFEEDER_API_LEGACY ("v1") — the legacy API, `Authorization: Token token=<token>`, JSON:API
+# page-number pagination (`page[number]`), account-scoped `/accounts/{id}/leads|visits` paths.
+# The generation Airbyte targets and the label existing source rows are pinned to. Deprecated by
+# the vendor (maintenance-only, no new tokens issued) but still served, with no announced sunset.
+#
+# LEADFEEDER_API_2026_08_07 — the unified Dealfront API, `X-Api-Key` on `/v1/*`, page-number
+# pagination via `page[num]` with a `meta.page_count` stop. This is the only generation new
+# customers can obtain credentials for, so it is the default for newly created sources. Its
+# stream shapes are implemented from the public OpenAPI spec (info.version 2026-08-07, marked
+# "work in progress") and warrant live verification before the source leaves alpha.
+
+# Opaque vendor labels — never parsed or ordered. LEADFEEDER_API_LEGACY equals the framework's
+# UNVERSIONED_API_VERSION ("v1"), which is the value migration 0075 backfilled onto existing rows.
+LEADFEEDER_API_LEGACY = "v1"
+LEADFEEDER_API_2026_08_07 = "2026-08-07"
+# Declare oldest -> newest; the default is always the last entry (enforced by test_source_versions).
+LEADFEEDER_SUPPORTED_VERSIONS = (LEADFEEDER_API_LEGACY, LEADFEEDER_API_2026_08_07)
+LEADFEEDER_DEFAULT_VERSION = LEADFEEDER_API_2026_08_07
def _date_field(name: str) -> IncrementalField:
@@ -32,9 +48,14 @@ def _datetime_field(name: str) -> IncrementalField:
@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.
+ # Legacy-API path relative to the base. Fan-out endpoints carry an `{account_id}` placeholder
+ # resolved per account at request time.
path: str
+ # Unified-API path for the same table. The table-name set is identical across versions (only the
+ # request path/shape differs) so discovery never orphans a table when a source is repinned.
+ unified_path: str
+ # Unified-API HTTP method. Web visits are a POST search on the unified API; everything else is GET.
+ unified_method: str = "GET"
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
@@ -57,15 +78,17 @@ LEADFEEDER_ENDPOINTS: dict[str, LeadfeederEndpointConfig] = {
"accounts": LeadfeederEndpointConfig(
name="accounts",
path="/accounts",
+ unified_path="/v1/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.
+ # Identified companies that visited the tracked site, one row per (account, company). The legacy
+ # `/accounts/{account_id}/leads` endpoint and the unified `/v1/web-visits/companies` endpoint both
+ # require a start_date/end_date range and filter 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",
+ unified_path="/v1/web-visits/companies",
primary_keys=["account_id", "id"],
partition_key="first_visit_date",
fan_out_over_accounts=True,
@@ -75,12 +98,14 @@ LEADFEEDER_ENDPOINTS: dict[str, LeadfeederEndpointConfig] = {
_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`.
+ # Individual website visits across the account. The legacy `/accounts/{account_id}/visits` GET and
+ # the unified `POST /v1/web-visits` search both take 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",
+ unified_path="/v1/web-visits",
+ unified_method="POST",
primary_keys=["account_id", "id"],
partition_key="started_at",
fan_out_over_accounts=True,
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.py
index 96c05dd1875b..9f7be653677b 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
@@ -9,7 +9,11 @@ from posthog.schema import (
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.base import (
+ FieldType,
+ ResumableSource,
+ VersionDeprecation,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -28,7 +32,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder
from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.settings import (
ENDPOINTS,
INCREMENTAL_FIELDS,
+ LEADFEEDER_API_LEGACY,
+ LEADFEEDER_DEFAULT_VERSION,
LEADFEEDER_ENDPOINTS,
+ LEADFEEDER_SUPPORTED_VERSIONS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -39,6 +46,13 @@ class LeadfeederSource(ResumableSource[LeadfeederSourceConfig, LeadfeederResumeC
api_docs_url = "https://docs.leadfeeder.com/api/"
+ supported_versions = LEADFEEDER_SUPPORTED_VERSIONS
+ default_version = LEADFEEDER_DEFAULT_VERSION
+ # The vendor has deprecated the legacy Token API (maintenance-only, no new tokens issued) in favor
+ # of the unified Dealfront API. No removal date is announced, so this is advisory (sunset_at=None):
+ # existing legacy-pinned sources keep working and are not migrated automatically.
+ deprecated_versions = (VersionDeprecation(version=LEADFEEDER_API_LEGACY, sunset_at=None),)
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.LEADFEEDER
@@ -51,11 +65,13 @@ class LeadfeederSource(ResumableSource[LeadfeederSourceConfig, LeadfeederResumeC
label="Leadfeeder",
releaseStatus=ReleaseStatus.ALPHA,
keywords=["dealfront"],
- caption="""Enter your Leadfeeder (Dealfront) API token to pull your website visitor and lead data into the PostHog Data warehouse.
+ caption="""Enter your Dealfront (Leadfeeder) API key to pull your website visitor and lead data into the PostHog data warehouse. This syncs the **Accounts**, **Leads**, and **Visits** tables.
+
+New connections use the unified Dealfront API. Create an API key in your Dealfront platform settings, under Personal, API keys.
-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.
+The older Leadfeeder API (a token from your [Leadfeeder API settings](https://app.leadfeeder.com/settings/api)) is deprecated and no longer issues new tokens. Existing connections on it keep working.
-Optionally set a **Start date** to bound the initial sync — leave it blank to pull the last year of leads and visits.""",
+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(
@@ -63,7 +79,7 @@ Optionally set a **Start date** to bound the initial sync — leave it blank to
[
SourceFieldInputConfig(
name="api_token",
- label="API token",
+ label="API key",
type=SourceFieldInputConfigType.PASSWORD,
required=True,
placeholder="",
@@ -106,6 +122,8 @@ Optionally set a **Start date** to bound the initial sync — leave it blank to
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
+ # Discovery is version-independent: both generations expose the same accounts / leads / visits
+ # tables with the same incremental fields, so the static catalog is identical whatever the pin.
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.
@@ -131,7 +149,9 @@ Optionally set a **Start date** to bound the initial sync — leave it blank to
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- if validate_leadfeeder_credentials(config.api_token):
+ # Pre-creation calls pass no pin and resolve to `default_version` (the unified API, what new
+ # rows are stamped with); a legacy-pinned source revalidates against its own Token API.
+ if validate_leadfeeder_credentials(config.api_token, self.resolve_api_version(api_version)):
return True, None
return (
@@ -160,4 +180,5 @@ Optionally set a **Start date** to bound the initial sync — leave it blank to
if inputs.should_use_incremental_field
else None,
incremental_field=inputs.incremental_field,
+ api_version=self.resolve_api_version(inputs.api_version),
)
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.py
index 91962a953163..959d45319c62 100644
--- 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.py
@@ -9,15 +9,24 @@ from unittest import mock
from parameterized import parameterized
from requests import Response
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.leadfeeder import (
LEADFEEDER_BASE_URL,
LeadfeederResumeConfig,
_default_start_date,
_flatten_item,
_to_date_str,
+ _unified_client_config,
+ _unified_headers,
leadfeeder_source,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.settings import (
+ LEADFEEDER_API_2026_08_07,
+ LEADFEEDER_API_LEGACY,
+)
# 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"
@@ -76,6 +85,38 @@ def _source(endpoint: str, manager: mock.MagicMock, **kwargs: Any):
return leadfeeder_source("token", endpoint, manager, team_id=1, job_id="j", **kwargs)
+def _unified_response(items: list[dict[str, Any]], page_count: int = 1) -> Response:
+ # The unified API reports the last page under `meta.page_count`; a single page stops pagination.
+ body: dict[str, Any] = {"data": items, "meta": {"page_num": 1, "page_count": page_count, "total_count": len(items)}}
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _wire_full(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session, snapshotting each request's method, url, params, and json body."""
+ session.headers = {}
+ requests: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ requests.append(
+ {
+ "method": request.method,
+ "url": request.url,
+ "params": dict(request.params or {}),
+ "json": request.json,
+ }
+ )
+ prepared = mock.MagicMock()
+ prepared.url = request.url
+ return prepared
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return requests
+
+
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)
@@ -302,3 +343,110 @@ class TestValidateCredentials:
validate_credentials("secret")
assert mock_session.call_args.kwargs["redact_values"] == ("secret",)
assert mock_session.call_args.kwargs["allow_redirects"] is False
+
+ @mock.patch(LEADFEEDER_SESSION_PATCH)
+ def test_unified_probe_uses_api_key_header_on_v1_accounts(self, mock_session: mock.MagicMock) -> None:
+ # A source pinned to the unified API must probe `/v1/accounts` with an `X-Api-Key` header,
+ # not the legacy `Authorization: Token` header on `/accounts`.
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ validate_credentials("secret", LEADFEEDER_API_2026_08_07)
+ call = mock_session.return_value.get.call_args
+ assert (call.args[0] if call.args else call.kwargs["url"]) == f"{LEADFEEDER_BASE_URL}/v1/accounts"
+ assert call.kwargs["headers"]["X-Api-Key"] == "secret"
+ assert "Authorization" not in call.kwargs["headers"]
+
+
+class TestUnifiedClientConfig:
+ def test_client_config_sends_api_key_header_and_page_number_pagination(self) -> None:
+ client = _unified_client_config("key123")
+ assert client["base_url"] == LEADFEEDER_BASE_URL
+ assert client["auth"] == {"type": "api_key", "api_key": "key123", "name": "X-Api-Key", "location": "header"}
+ paginator = client["paginator"]
+ assert isinstance(paginator, PageNumberPaginator)
+ assert paginator.page_param == "page[num]"
+
+ def test_headers_carry_api_key(self) -> None:
+ assert _unified_headers("key123")["X-Api-Key"] == "key123"
+
+
+class TestUnifiedRequests:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_accounts_hits_v1_path_with_page_params(self, MockSession) -> None:
+ session = MockSession.return_value
+ requests = _wire_full(session, [_unified_response([_item("1", "account", name="A")])])
+ rows = _rows(_source("accounts", _make_manager(), api_version=LEADFEEDER_API_2026_08_07))
+
+ assert rows == [{"id": "1", "type": "account", "name": "A"}]
+ assert requests[0]["url"] == f"{LEADFEEDER_BASE_URL}/v1/accounts"
+ assert requests[0]["params"]["page[num]"] == 1
+ assert requests[0]["params"]["page[size]"] == 100
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_accounts_pagination_stops_without_meta_page_count(self, MockSession) -> None:
+ # The real /v1/accounts endpoint returns its whole result set in one response with no
+ # `meta.page_count` field at all (unlike the paginated child endpoints, modelled by
+ # _unified_response). The client-level PageNumberPaginator's total-pages stop check silently
+ # no-ops when that field is missing, and the page is never empty either, so it would otherwise
+ # keep requesting page[num]=2, 3, ... forever. Accounts must use a paginator that always stops
+ # after a single page regardless of what the response body contains.
+ session = MockSession.return_value
+ body = {"data": [{"id": "1", "type": "account", "attributes": {}}]}
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ requests = _wire_full(session, [resp])
+
+ rows = _rows(_source("accounts", _make_manager(), api_version=LEADFEEDER_API_2026_08_07))
+
+ assert rows == [{"id": "1", "type": "account"}]
+ assert len(requests) == 1
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @freeze_time("2026-07-02")
+ def test_leads_fan_out_hits_visitor_companies_with_account_id_query(self, MockSession) -> None:
+ session = MockSession.return_value
+ requests = _wire_full(
+ session,
+ [
+ _unified_response([_item("1", "account"), _item("2", "account")]),
+ _unified_response([_item("100", "company_location")]),
+ _unified_response([_item("200", "company_location")]),
+ ],
+ )
+ _rows(_source("leads", _make_manager(), start_date_config="2024-01-01", api_version=LEADFEEDER_API_2026_08_07))
+
+ company_reqs = [r for r in requests if "/v1/web-visits/companies" in r["url"]]
+ # account id is a query param on the unified API (a path segment on the legacy API).
+ assert {r["params"]["account_id"] for r in company_reqs} == {"1", "2"}
+ assert company_reqs[0]["params"]["start_date"] == "2024-01-01"
+ assert company_reqs[0]["params"]["end_date"] == "2026-07-02"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ @freeze_time("2026-07-02")
+ def test_visits_fan_out_posts_web_visits_with_date_body(self, MockSession) -> None:
+ session = MockSession.return_value
+ requests = _wire_full(
+ session,
+ [
+ _unified_response([_item("1", "account")]),
+ _unified_response([_item("100", "web_visit", started_at="2026-06-01T10:00:00Z")]),
+ ],
+ )
+ _rows(_source("visits", _make_manager(), start_date_config="2024-01-01", api_version=LEADFEEDER_API_2026_08_07))
+
+ visit_reqs = [r for r in requests if r["url"].endswith("/v1/web-visits")]
+ assert visit_reqs, "expected a request to the unified web-visits search"
+ # The web-visits search is a POST carrying its date window in the body, not the query string.
+ assert visit_reqs[0]["method"] == "POST"
+ assert visit_reqs[0]["json"] == {"start_date": "2024-01-01", "end_date": "2026-07-02"}
+ assert visit_reqs[0]["params"]["account_id"] == "1"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_legacy_pin_still_uses_token_api_paths(self, MockSession) -> None:
+ # The legacy request path must be unchanged for sources still pinned to it.
+ session = MockSession.return_value
+ requests = _wire_full(session, [_response([_item("1", "accounts", name="A")])])
+ _rows(_source("accounts", _make_manager(), api_version=LEADFEEDER_API_LEGACY))
+
+ assert requests[0]["url"] == f"{LEADFEEDER_BASE_URL}/accounts"
+ assert requests[0]["params"]["page[number]"] == 1
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.py
index 92463efce411..e54aa3f071c5 100644
--- 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.py
@@ -4,6 +4,7 @@ from parameterized import parameterized
from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import VersionDeprecation
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.leadfeeder import (
LeadfeederSourceConfig,
@@ -11,7 +12,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
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.settings import (
+ ENDPOINTS,
+ LEADFEEDER_API_2026_08_07,
+ LEADFEEDER_API_LEGACY,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.source import LeadfeederSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -43,6 +48,13 @@ class TestLeadfeederSource:
assert token_field.secret is True
assert token_field.required is True
+ def test_version_metadata_defaults_to_unified_and_deprecates_legacy(self) -> None:
+ # New sources land on the unified Dealfront API; the legacy Token API is advisory-deprecated
+ # (no announced sunset), which is why existing pins are not migrated automatically.
+ assert self.source.supported_versions == (LEADFEEDER_API_LEGACY, LEADFEEDER_API_2026_08_07)
+ assert self.source.default_version == LEADFEEDER_API_2026_08_07
+ assert self.source.deprecated_versions == (VersionDeprecation(version=LEADFEEDER_API_LEGACY, sunset_at=None),)
+
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
@@ -105,7 +117,21 @@ class TestLeadfeederSource:
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")
+ # No pin at creation time resolves to the default (unified) version.
+ mock_validate.assert_called_once_with("token", LEADFEEDER_API_2026_08_07)
+
+ @parameterized.expand([(None, LEADFEEDER_API_2026_08_07), (LEADFEEDER_API_LEGACY, LEADFEEDER_API_LEGACY)])
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.leadfeeder.source.validate_leadfeeder_credentials"
+ )
+ def test_validate_credentials_probes_under_the_pinned_version(
+ self, pin: str | None, expected_version: str, mock_validate: mock.MagicMock
+ ) -> None:
+ # A legacy-pinned source must probe the legacy API, not the resolved default — otherwise a
+ # valid legacy token would fail validation against the unified endpoint.
+ mock_validate.return_value = True
+ self.source.validate_credentials(self.config, self.team_id, api_version=pin)
+ mock_validate.assert_called_once_with("token", expected_version)
def test_get_resumable_source_manager_binds_resume_config(self) -> None:
manager = self.source.get_resumable_source_manager(mock.MagicMock())
@@ -118,6 +144,7 @@ class TestLeadfeederSource:
inputs.schema_name = "leads"
inputs.should_use_incremental_field = True
inputs.db_incremental_field_last_value = "2024-06-01"
+ inputs.api_version = LEADFEEDER_API_LEGACY
manager = mock.MagicMock()
self.source.source_for_pipeline(self.config, manager, inputs)
@@ -128,6 +155,8 @@ class TestLeadfeederSource:
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"
+ # The resolved source pin reaches the request layer so it builds the right generation's client.
+ assert kwargs["api_version"] == LEADFEEDER_API_LEGACY
@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: