: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 linkrunner import source (#67830)
Tom Owers9c01711d1147
diff --git a/frontend/public/services/linkrunner.png b/frontend/public/services/linkrunner.pngdeleted file mode 100644index ec1d9e917163..000000000000Binary files a/frontend/public/services/linkrunner.png and /dev/null differdiff --git a/frontend/public/services/linkrunner.svg b/frontend/public/services/linkrunner.svgnew file mode 100644index 000000000000..28cbe512fe41--- /dev/null+++ b/frontend/public/services/linkrunner.svg@@ -0,0 +1,9 @@+<svg width="256" height="256" viewBox="0 0 360 360" fill="none" xmlns="http://www.w3.org/2000/svg" aria-label="Linkrunner logo mark">+ <rect width="360" height="360" rx="80" fill="#4D4BF7"/>+ <rect x="50" y="50" width="125" height="120" fill="#FFFFFF"/>+ <rect x="50" y="180" width="125" height="80" fill="#FFFFFF"/>+ <rect x="50" y="270" width="125" height="40" fill="#FFFFFF"/>+ <rect x="185" y="50" width="125" height="40" fill="#FFFFFF" opacity="0.4"/>+ <rect x="185" y="100" width="125" height="80" fill="#FFFFFF" opacity="0.4"/>+ <rect x="185" y="190" width="125" height="120" fill="#FFFFFF"/>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 29855ff52ece..6e226323d032 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -205,6 +205,7 @@ the row lists both.| linear | HTTP | requests | ✅ || lever | HTTP | requests | ✅ || linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |+| linkrunner | HTTP | requests | ✅ || lob | HTTP | requests | ✅ || mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ || mailerlite | HTTP | requests | ✅ |@@ -513,7 +514,6 @@ doesn't conflict with concurrent PRs.- liana- lightfield- linkedin_pages-- linkrunner- linnworks- lokalise- lookerdiff --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 582679a6b52e..284d0de16a49 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@@ -1863,7 +1863,7 @@ class LinkedinPagesSourceConfig(config.Config):@config.configclass LinkrunnerSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/canonical_descriptions.pynew file mode 100644index 000000000000..6977671bb9d9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/canonical_descriptions.py@@ -0,0 +1,69 @@+"""Canonical, documentation-sourced descriptions for Linkrunner endpoints and columns.++Sourced from the official Linkrunner API reference (https://docs.linkrunner.io/api-reference/data-apis).+Keyed by the endpoint names in `settings.py` `LINKRUNNER_ENDPOINTS`, which match the+`ExternalDataSchema.name` of a synced Linkrunner table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "campaigns": {+ "description": "All campaigns configured in your Linkrunner account, including their tracking links and store listings.",+ "docs_url": "https://docs.linkrunner.io/api-reference/data-apis",+ "columns": {+ "display_id": "The campaign's unique display identifier, used across the Linkrunner API.",+ "name": "Human-readable campaign name.",+ "created_at": "Time at which the campaign was created (ISO 8601).",+ "update_at": "Time at which the campaign was last updated (ISO 8601).",+ "google": "Whether the campaign is linked to a Google Ads source.",+ "meta": "Whether the campaign is linked to a Meta (Facebook/Instagram) Ads source.",+ "meta_campaign_id": "The associated Meta campaign identifier, if any.",+ "meta_web_to_app": "Whether the campaign uses Meta's web-to-app flow.",+ "active": "Whether the campaign is currently active.",+ "default_link": "The default deep link for the campaign.",+ "attributed_users": "Count of users attributed to the campaign.",+ "link": "The campaign's tracking link.",+ "shareable_link": "A shareable version of the campaign's link.",+ "domain": "The domain used for the campaign's links.",+ "store_listings": "Store listings (App Store / Play Store configurations) attached to the campaign.",+ },+ },+ "attributed_users": {+ "description": "Users attributed to a campaign, with attribution metadata, ad-network details, and device data.",+ "docs_url": "https://docs.linkrunner.io/api-reference/data-apis",+ "columns": {+ "campaign_display_id": "Display identifier of the campaign the user was attributed to.",+ "campaign_name": "Name of the campaign the user was attributed to.",+ "attributed_at": "Time at which the user was attributed to the campaign (ISO 8601).",+ "installed_at": "Time at which the app was installed (ISO 8601).",+ "store_click_at": "Time at which the store listing was clicked (ISO 8601).",+ "ad_channel": "The ad channel that drove the attribution (e.g. Google, Meta).",+ "link": "The tracking link the user came through.",+ "meta_ad_id": "Meta ad identifier associated with the attribution.",+ "ad_creative_id": "Identifier of the ad creative.",+ "ad_creative_name": "Name of the ad creative.",+ "ad_set_id": "Identifier of the ad set.",+ "ad_set_name": "Name of the ad set.",+ "publisher_platform": "The publisher platform where the ad was shown.",+ "platform_position": "The position/placement of the ad on the platform.",+ "user_id": "Linkrunner user identifier (lifted from the nested user_data object).",+ "user_name": "Name provided for the attributed user.",+ "user_email": "Email provided for the attributed user.",+ "user_phone": "Phone number provided for the attributed user.",+ "device_data": "Device metadata for the attributed user (brand, OS, device id, etc.).",+ },+ },+ "reporting_campaigns": {+ "description": "Campaign-level performance metrics from the Reporting API: clicks, installs, signups, spend, revenue, ROAS, ad sets, ad creatives, and keywords.",+ "docs_url": "https://docs.linkrunner.io/api-reference/reporting-campaigns",+ "columns": {+ "id": "Numeric unique identifier for the campaign.",+ "display_id": "The campaign's unique display identifier.",+ "name": "Human-readable campaign name.",+ "created_at": "Time at which the campaign was created (ISO 8601).",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.pynew file mode 100644index 000000000000..11019331d2f8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/linkrunner.py@@ -0,0 +1,357 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher+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.linkrunner.settings import (+ LINKRUNNER_ENDPOINTS,+ LinkrunnerEndpointConfig,+)++LINKRUNNER_BASE_URL = "https://api.linkrunner.io/api/v1"++# Default wait when a 429 arrives without a usable Retry-After header. The reporting API documents a+# 1 request/minute limit with Retry-After: 60, so 60s is the safe fallback.+_DEFAULT_RETRY_AFTER_SECONDS = 60+++class LinkrunnerRetryableError(Exception):+ pass+++class LinkrunnerRateLimitError(Exception):+ def __init__(self, retry_after: int) -> None:+ super().__init__(f"Linkrunner rate limit hit; retry after {retry_after}s")+ self.retry_after = retry_after+++class LinkrunnerResumeConfig:+ # Next page (1-indexed) to fetch for the current resource / campaign.+ page: int = 1+ # Fan-out bookmark: the campaign display_id currently being paged. None for top-level endpoints.+ campaign_display_id: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"linkrunner-key": api_key, "Accept": "application/json"}+++def _format_timestamp(value: Any) -> str:+ """Format an incremental cursor value as ISO 8601 UTC with a `Z` suffix.++ Linkrunner documents ISO 8601 timestamps in UTC by default. The cursor comes back as a+ datetime, date, or already-formatted string depending on how it was stored.+ """+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def _parse_retry_after(response: "requests.Response") -> int:+ raw = response.headers.get("Retry-After")+ if raw:+ try:+ return max(1, int(raw))+ except ValueError:+ pass+ return _DEFAULT_RETRY_AFTER_SECONDS+++def _has_next_page(page: int, total_pages: Any, num_items: int, limit: int) -> bool:+ """Decide whether to fetch another page.++ Prefer the server's reported page count; fall back to "a full page implies more" when the+ pagination block is missing, and always stop on an empty page.+ """+ if num_items == 0:+ return False+ if isinstance(total_pages, int):+ return page < total_pages+ return num_items >= limit+++def _wait_for_retry(retry_state: RetryCallState) -> float:+ """Respect the API's Retry-After on rate limits; otherwise exponential backoff with jitter."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, LinkrunnerRateLimitError):+ return float(exc.retry_after)+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++@retry(+ retry=retry_if_exception_type(+ (+ LinkrunnerRetryableError,+ LinkrunnerRateLimitError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(8),+ wait=_wait_for_retry,+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ headers: dict[str, str],+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> Optional[dict]:+ """Fetch one page. Returns the parsed body, or None when the API replies 204 No Content."""+ response = session.get(f"{LINKRUNNER_BASE_URL}{path}", headers=headers, params=params, timeout=60)++ # Several Linkrunner endpoints return 204 with an empty body when there's no data to return.+ if response.status_code == 204:+ return None++ if response.status_code == 429:+ retry_after = _parse_retry_after(response)+ logger.warning(f"Linkrunner rate limit hit on {path}; retrying after {retry_after}s")+ raise LinkrunnerRateLimitError(retry_after)++ if response.status_code >= 500:+ raise LinkrunnerRetryableError(f"Linkrunner API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"Linkrunner API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ return response.json()+++def validate_credentials(api_key: str) -> bool:+ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{LINKRUNNER_BASE_URL}/campaigns", headers=_get_headers(api_key), params={"limit": 1}, timeout=10+ )+ return response.status_code in (200, 204)+ except Exception:+ return False+++def _flatten_attributed_user(item: dict[str, Any]) -> dict[str, Any]:+ """Promote the nested `user_data` object to top-level `user_*` columns.++ `user_id` becomes a first-class column so it can be part of the primary key; the richer+ `device_data` object is kept nested under the row.+ """+ row = dict(item)+ user_data = row.pop("user_data", None)+ if isinstance(user_data, dict):+ # `user_id` is part of the primary key, so index directly: a missing id must fail loudly+ # rather than write None and seed a phantom, non-deduping row.+ row["user_id"] = user_data["id"]+ row["user_name"] = user_data.get("name")+ row["user_email"] = user_data.get("email")+ row["user_phone"] = user_data.get("phone")+ row["device_data"] = user_data.get("device_data")+ return row+++def _iter_campaign_display_ids(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[str]:+ """Page through /campaigns and yield each campaign's display_id (used to seed the fan-out)."""+ config = LINKRUNNER_ENDPOINTS["campaigns"]+ page = 1+ while True:+ data = _fetch_page(session, config.path, headers, {"page": page, "limit": config.default_limit}, logger)+ if data is None:+ break+ payload = data.get("data") or {}+ items = payload.get("campaigns") or []+ for item in items:+ display_id = item.get("display_id")+ if display_id is not None:+ yield display_id++ pagination = payload.get("pagination") or {}+ if not _has_next_page(page, pagination.get("pages"), len(items), config.default_limit):+ break+ page += 1+++def _get_list_rows(+ session: requests.Session,+ config: LinkrunnerEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[LinkrunnerResumeConfig],+ start_timestamp: str | None,+) -> Iterator[Any]:+ """Page a top-level list endpoint (campaigns / reporting_campaigns)."""+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume.page if resume is not None and resume.campaign_display_id is None else 1++ while True:+ params: dict[str, Any] = {"page": page, "limit": config.default_limit}+ if start_timestamp and config.incremental_start_param:+ params[config.incremental_start_param] = start_timestamp++ data = _fetch_page(session, config.path, headers, params, logger)+ if data is None:+ break++ payload = data.get("data") or {}+ items = payload.get(config.data_key) or []+ pagination = payload.get("pagination") or {}+ has_next = _has_next_page(page, pagination.get("pages"), len(items), config.default_limit)++ for item in items:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding (only when more pages remain) so a crash re-yields the last+ # page rather than skipping it — merge dedupes on the primary key.+ if has_next:+ resumable_source_manager.save_state(LinkrunnerResumeConfig(page=page + 1))++ if not has_next:+ break+ page += 1+++def _get_attributed_user_rows(+ session: requests.Session,+ config: LinkrunnerEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ batcher: Batcher,+ resumable_source_manager: ResumableSourceManager[LinkrunnerResumeConfig],+ start_timestamp: str | None,+) -> Iterator[Any]:+ """Fan out over every campaign, paging /attributed-users per campaign display_id."""+ campaign_ids = list(_iter_campaign_display_ids(session, headers, logger))++ # Resolve the saved campaign bookmark to the slice still to process. If the bookmarked campaign no+ # longer exists (deleted between runs), start over — merge dedupes on the primary key.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = campaign_ids+ resume_page = 1+ if resume is not None and resume.campaign_display_id is not None and resume.campaign_display_id in campaign_ids:+ remaining = campaign_ids[campaign_ids.index(resume.campaign_display_id) :]+ resume_page = resume.page+ logger.debug(+ f"Linkrunner: resuming attributed_users from campaign={resume.campaign_display_id}, page={resume_page}"+ )++ for index, display_id in enumerate(remaining):+ page = resume_page+ resume_page = 1 # only the resumed-into campaign uses the saved page; the rest start at 1++ while True:+ params: dict[str, Any] = {"display_id": display_id, "page": page, "limit": config.default_limit}+ if start_timestamp:+ params["start_timestamp"] = start_timestamp++ data = _fetch_page(session, config.path, headers, params, logger)+ if data is None: # 204 — campaign has no attributed users in range+ break++ payload = data.get("data") or {}+ items = payload.get(config.data_key) or []+ pagination = payload.get("pagination") or {}+ has_next = _has_next_page(page, pagination.get("pages"), len(items), config.default_limit)++ for item in items:+ batcher.batch(_flatten_attributed_user(item))+ if batcher.should_yield():+ yield batcher.get_table()+ if has_next:+ resumable_source_manager.save_state(+ LinkrunnerResumeConfig(page=page + 1, campaign_display_id=display_id)+ )++ if not has_next:+ break+ page += 1++ # Advance the bookmark to the next campaign so a crash between campaigns resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(+ LinkrunnerResumeConfig(page=1, campaign_display_id=remaining[index + 1])+ )+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LinkrunnerResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = LINKRUNNER_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page (and every campaign, for the fan-out) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. Redact the API key from tracked logs /+ # captured samples — it rides a nonstandard `linkrunner-key` header the denylist can't predict.+ session = make_tracked_session(redact_values=(api_key,))++ start_timestamp = (+ _format_timestamp(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )++ if config.fan_out_over_campaigns:+ yield from _get_attributed_user_rows(+ session, config, headers, logger, batcher, resumable_source_manager, start_timestamp+ )+ else:+ yield from _get_list_rows(session, config, headers, logger, batcher, resumable_source_manager, start_timestamp)++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def linkrunner_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LinkrunnerResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = LINKRUNNER_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ # Linkrunner doesn't document a sort order and exposes no sort param. The pipeline computes the+ # incremental watermark as the max value seen and only commits it on success, and this source is+ # resumable, so ascending-order assumptions aren't relied upon for correctness here.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/settings.pynew file mode 100644index 000000000000..f5b76c8504de--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/settings.py@@ -0,0 +1,84 @@+from dataclasses import dataclass+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class LinkrunnerEndpointConfig:+ name: str+ path: str+ # Key inside the response `data` object that holds the row list (e.g. "campaigns", "users").+ data_key: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField]+ # Stable datetime column to partition by (never an `updated_at`-style field).+ partition_key: Optional[str] = None+ default_limit: int = 100+ # Server-side timestamp filter param, set only where the API genuinely filters rows by it.+ incremental_start_param: Optional[str] = None+ # Fan out one paginated request per campaign, substituting each campaign's `display_id`.+ fan_out_over_campaigns: bool = False+ # Reporting API is capped at 1 request/minute/key (429 + Retry-After: 60); pace accordingly.+ rate_limited_per_minute: bool = False+ should_sync_default: bool = True+++_ATTRIBUTED_AT_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "attributed_at",+ "type": IncrementalFieldType.DateTime,+ "field": "attributed_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++LINKRUNNER_ENDPOINTS: dict[str, LinkrunnerEndpointConfig] = {+ # Campaign list. No server-side timestamp filter is exposed (only filter/channel/domain/link),+ # so this is full refresh. `display_id` is the campaign's unique identifier across the API.+ "campaigns": LinkrunnerEndpointConfig(+ name="campaigns",+ path="/campaigns",+ data_key="campaigns",+ primary_keys=["display_id"],+ partition_key="created_at",+ default_limit=1000, # max page size — minimise page count for a full-refresh list+ incremental_fields=[],+ ),+ # Users attributed to a campaign. Requires a per-campaign `display_id`, so we fan out over the+ # campaign list. `start_timestamp` genuinely filters which users are returned (per the API docs),+ # so this endpoint supports incremental sync on `attributed_at`.+ "attributed_users": LinkrunnerEndpointConfig(+ name="attributed_users",+ path="/attributed-users",+ data_key="users",+ # No documented per-record id, so the natural key is (campaign, user, attribution time).+ # `campaign_display_id` keeps the key unique table-wide across the fan-out.+ primary_keys=["campaign_display_id", "user_id", "attributed_at"],+ partition_key="attributed_at",+ default_limit=1000,+ incremental_start_param="start_timestamp",+ fan_out_over_campaigns=True,+ incremental_fields=_ATTRIBUTED_AT_INCREMENTAL,+ ),+ # Campaign-level performance metrics (clicks, installs, spend, revenue, ROAS, ...). The `from`/`to`+ # params only window the metrics, they don't filter the row list, so this is full refresh. Rate+ # limited to 1 request/minute/key.+ "reporting_campaigns": LinkrunnerEndpointConfig(+ name="reporting_campaigns",+ path="/reporting/campaigns",+ data_key="campaigns",+ primary_keys=["display_id"],+ partition_key="created_at",+ default_limit=100, # reporting caps `limit` at 100 (larger values 422)+ rate_limited_per_minute=True,+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(LINKRUNNER_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LINKRUNNER_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/source.pyindex a44cc5ebefbf..7369c4e42de6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/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 LinkrunnerSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner.linkrunner import (+ LinkrunnerResumeConfig,+ linkrunner_source,+ validate_credentials as validate_linkrunner_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ LINKRUNNER_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LinkrunnerSource(SimpleSource[LinkrunnerSourceConfig]):+class LinkrunnerSource(ResumableSource[LinkrunnerSourceConfig, LinkrunnerResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LINKRUNNER@@ -24,7 +48,105 @@ class LinkrunnerSource(SimpleSource[LinkrunnerSourceConfig]):name=SchemaExternalDataSourceType.LINKRUNNER,category=DataWarehouseSourceCategory.ADVERTISING,label="Linkrunner",- iconPath="/static/services/linkrunner.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Linkrunner API key to pull your mobile attribution data into the PostHog Data warehouse.++You can find your API key in your [Linkrunner dashboard](https://www.linkrunner.io/) under settings.++Note: the `reporting_campaigns` table is served by Linkrunner's Reporting API, which is rate limited to **1 request per minute**, so syncing it can take a while for accounts with many campaigns.+""",+ iconPath="/static/services/linkrunner.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/linkrunner",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or missing Linkrunner key surfaces as a 401 when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.+ "401 Client Error: Unauthorized for url: https://api.linkrunner.io": "Your Linkrunner API key is invalid or has been revoked. Create a new key in your Linkrunner dashboard, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.linkrunner.io": "Your Linkrunner API key does not have access to this data. Check the key's permissions in your Linkrunner dashboard, then reconnect.",+ }++ def get_schemas(+ self,+ config: LinkrunnerSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "reporting_campaigns":+ return "Campaign performance metrics. Served by the rate-limited Reporting API (1 request/minute). Full refresh only."+ if endpoint == "campaigns":+ return "All campaigns in your Linkrunner account. Full refresh only."+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = LINKRUNNER_ENDPOINTS[endpoint]+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=endpoint_config.primary_keys,+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),+ )++ 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: LinkrunnerSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_linkrunner_credentials(config.api_key):+ return True, None++ return False, "Invalid Linkrunner API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LinkrunnerResumeConfig]:+ return ResumableSourceManager[LinkrunnerResumeConfig](inputs, LinkrunnerResumeConfig)++ def source_for_pipeline(+ self,+ config: LinkrunnerSourceConfig,+ resumable_source_manager: ResumableSourceManager[LinkrunnerResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return linkrunner_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner.pynew file mode 100644index 000000000000..c991d270c557--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner.py@@ -0,0 +1,285 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner import linkrunner+from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner.linkrunner import (+ LinkrunnerRateLimitError,+ LinkrunnerResumeConfig,+ LinkrunnerRetryableError,+ _flatten_attributed_user,+ _format_timestamp,+ _has_next_page,+ _parse_retry_after,+ get_rows,+ validate_credentials,+)+++class TestFormatTimestamp:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),+ ]+ )+ def test_format_timestamp(self, _name: str, value: Any, expected: str) -> None:+ # A wrong timestamp shape silently breaks the server-side start_timestamp filter, so lock the ISO-8601 Z form.+ assert _format_timestamp(value) == expected++ def test_no_plus_zero_offset(self) -> None:+ assert "+00:00" not in _format_timestamp(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))+++class TestHasNextPage:+ @parameterized.expand(+ [+ # (page, total_pages, num_items, limit, expected)+ ("more_pages_by_count", 1, 4, 100, 100, True),+ ("last_page_by_count", 4, 4, 100, 50, False),+ ("empty_page_always_stops", 2, 9, 0, 100, False),+ ("full_page_no_pagination_block", 1, None, 100, 100, True),+ ("partial_page_no_pagination_block", 1, None, 30, 100, False),+ ]+ )+ def test_has_next_page(+ self, _name: str, page: int, total_pages: Any, num_items: int, limit: int, expected: bool+ ) -> None:+ assert _has_next_page(page, total_pages, num_items, limit) is expected+++class TestFlattenAttributedUser:+ def test_promotes_user_id_to_top_level(self) -> None:+ # user_id is part of the primary key, so it must exist as a top-level column, not stay nested.+ row = _flatten_attributed_user(+ {+ "campaign_display_id": "C1",+ "attributed_at": "2026-01-01T00:00:00Z",+ "user_data": {"id": "U1", "name": "Ada", "email": "[email protected]", "phone": "1", "device_data": {"brand": "x"}},+ }+ )+ assert row["user_id"] == "U1"+ assert row["user_name"] == "Ada"+ assert row["user_email"] == "[email protected]"+ assert row["user_phone"] == "1"+ assert row["device_data"] == {"brand": "x"}+ assert "user_data" not in row++ def test_missing_user_data_leaves_row_intact(self) -> None:+ row = _flatten_attributed_user({"campaign_display_id": "C1", "attributed_at": "t"})+ assert row == {"campaign_display_id": "C1", "attributed_at": "t"}+++class TestParseRetryAfter:+ @parameterized.expand(+ [+ ("valid_seconds", {"Retry-After": "45"}, 45),+ ("missing_header_defaults_to_60", {}, 60),+ ("non_numeric_defaults_to_60", {"Retry-After": "soon"}, 60),+ ]+ )+ def test_parse_retry_after(self, _name: str, headers: dict[str, str], expected: int) -> None:+ response = requests.Response()+ response.headers.update(headers)+ assert _parse_retry_after(response) == expected+++class _FakeResumableManager:+ def __init__(self, state: LinkrunnerResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[LinkrunnerResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> LinkrunnerResumeConfig | None:+ return self._state++ def save_state(self, data: LinkrunnerResumeConfig) -> None:+ self.saved.append(data)+++def _body(data_key: str, items: list[dict], pages: int) -> dict:+ return {"data": {data_key: items, "pagination": {"total": len(items), "pages": pages, "page": 1, "limit": 1000}}}+++def _make_fake_fetch(responses: dict, calls: list | None = None):+ def fake_fetch(session: Any, path: str, headers: dict, params: dict, logger: Any) -> Any:+ if calls is not None:+ calls.append((path, dict(params)))+ key = (path, params.get("page", 1), params.get("display_id"))+ result = responses.get(key)+ if isinstance(result, Exception):+ raise result+ return result++ return fake_fetch+++def _collect(+ manager: _FakeResumableManager, endpoint: str, monkeypatch: Any, responses: dict, **kwargs: Any+) -> list[dict]:+ monkeypatch.setattr(linkrunner, "_fetch_page", _make_fake_fetch(responses))+ rows: list[dict] = []+ for table in get_rows(+ api_key="k",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(table.to_pylist())+ return rows+++class TestCampaignsPagination:+ def test_follows_pages_until_last(self, monkeypatch: Any) -> None:+ responses = {+ ("/campaigns", 1, None): _body("campaigns", [{"display_id": "C1"}], pages=2),+ ("/campaigns", 2, None): _body("campaigns", [{"display_id": "C2"}], pages=2),+ }+ rows = _collect(_FakeResumableManager(), "campaigns", monkeypatch, responses)+ assert [r["display_id"] for r in rows] == ["C1", "C2"]++ def test_resume_starts_from_saved_page(self, monkeypatch: Any) -> None:+ # A resumed list sync must continue at the saved page, not restart at page 1.+ calls: list = []+ responses = {("/campaigns", 3, None): _body("campaigns", [{"display_id": "C3"}], pages=3)}+ monkeypatch.setattr(linkrunner, "_fetch_page", _make_fake_fetch(responses, calls))+ rows: list[dict] = []+ for table in get_rows(+ api_key="k",+ endpoint="campaigns",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(LinkrunnerResumeConfig(page=3)), # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())+ assert [r["display_id"] for r in rows] == ["C3"]+ assert calls[0][1]["page"] == 3++ def test_204_yields_no_rows(self, monkeypatch: Any) -> None:+ responses = {("/campaigns", 1, None): None}+ rows = _collect(_FakeResumableManager(), "campaigns", monkeypatch, responses)+ assert rows == []+++class TestAttributedUsersFanOut:+ def _responses_two_campaigns(self) -> dict:+ return {+ ("/campaigns", 1, None): _body("campaigns", [{"display_id": "C1"}, {"display_id": "C2"}], pages=1),+ ("/attributed-users", 1, "C1"): _body(+ "users",+ [{"campaign_display_id": "C1", "attributed_at": "t1", "user_data": {"id": "U1"}}],+ pages=1,+ ),+ ("/attributed-users", 1, "C2"): _body(+ "users",+ [{"campaign_display_id": "C2", "attributed_at": "t2", "user_data": {"id": "U2"}}],+ pages=1,+ ),+ }++ def test_fans_out_over_campaigns_and_flattens_keys(self, monkeypatch: Any) -> None:+ rows = _collect(_FakeResumableManager(), "attributed_users", monkeypatch, self._responses_two_campaigns())+ # Every row carries the parent campaign id and a top-level user_id (the composite primary key).+ assert {(r["campaign_display_id"], r["user_id"]) for r in rows} == {("C1", "U1"), ("C2", "U2")}++ def test_advances_bookmark_between_campaigns(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ _collect(manager, "attributed_users", monkeypatch, self._responses_two_campaigns())+ # After finishing C1 the bookmark must point at C2 so a crash resumes at the next campaign, not the first.+ assert LinkrunnerResumeConfig(page=1, campaign_display_id="C2") in manager.saved++ def test_resume_from_bookmark_skips_completed_campaigns(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(LinkrunnerResumeConfig(page=1, campaign_display_id="C2"))+ rows = _collect(manager, "attributed_users", monkeypatch, self._responses_two_campaigns())+ assert [r["user_id"] for r in rows] == ["U2"]++ def test_incremental_passes_start_timestamp(self, monkeypatch: Any) -> None:+ calls: list = []+ responses = {+ ("/campaigns", 1, None): _body("campaigns", [{"display_id": "C1"}], pages=1),+ ("/attributed-users", 1, "C1"): _body(+ "users", [{"campaign_display_id": "C1", "attributed_at": "t1", "user_data": {"id": "U1"}}], pages=1+ ),+ }+ monkeypatch.setattr(linkrunner, "_fetch_page", _make_fake_fetch(responses, calls))+ list(+ get_rows(+ api_key="k",+ endpoint="attributed_users",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ )+ )+ attributed_calls = [params for path, params in calls if path == "/attributed-users"]+ assert attributed_calls[0]["start_timestamp"] == "2026-03-04T02:58:14Z"+++class TestFetchPage:+ def _response(self, status: int, headers: dict | None = None, body: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status+ response.ok = 200 <= status < 300+ response.headers = headers or {}+ response.json.return_value = body or {}+ return response++ def test_204_returns_none(self) -> None:+ session = MagicMock()+ session.get.return_value = self._response(204)+ assert linkrunner._fetch_page(session, "/campaigns", {}, {}, MagicMock()) is None++ def test_429_raises_rate_limit_error_with_retry_after(self) -> None:+ session = MagicMock()+ session.get.return_value = self._response(429, headers={"Retry-After": "60"})+ with patch.object(linkrunner._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ with pytest.raises(LinkrunnerRateLimitError) as exc:+ linkrunner._fetch_page(session, "/reporting/campaigns", {}, {}, MagicMock())+ assert exc.value.retry_after == 60++ def test_retries_5xx_then_succeeds(self) -> None:+ session = MagicMock()+ session.get.side_effect = [self._response(503), self._response(200, body={"data": {}})]+ with patch.object(linkrunner._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]+ result = linkrunner._fetch_page(session, "/campaigns", {}, {}, MagicMock())+ assert result == {"data": {}}+ assert session.get.call_count == 2++ @parameterized.expand(+ [+ ("rate_limit", LinkrunnerRateLimitError(1)),+ ("retryable", LinkrunnerRetryableError("boom")),+ ("read_timeout", requests.ReadTimeout("timeout")),+ ]+ )+ def test_retryable_error_types(self, _name: str, exc: Exception) -> None:+ # These are the error types the retry decorator must keep retrying rather than fail the sync on.+ retry_types = linkrunner._fetch_page.retry.retry.exception_types # type: ignore[attr-defined]+ assert isinstance(exc, retry_types)+++class TestValidateCredentials:+ @parameterized.expand([("ok", 200, True), ("no_content", 204, True), ("unauthorized", 401, False)])+ def test_status_maps_to_validity(self, _name: str, status: int, expected: bool) -> None:+ response = MagicMock()+ response.status_code = status+ session = MagicMock()+ session.get.return_value = response+ with patch.object(linkrunner, "make_tracked_session", return_value=session):+ assert validate_credentials("key") is expected++ def test_network_failure_is_invalid(self) -> None:+ session = MagicMock()+ session.get.side_effect = requests.ConnectionError("down")+ with patch.object(linkrunner, "make_tracked_session", return_value=session):+ assert validate_credentials("key") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner_source.pynew file mode 100644index 000000000000..c17d9330de62--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkrunner/tests/test_linkrunner_source.py@@ -0,0 +1,141 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ 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.linkrunner import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner.linkrunner import (+ LinkrunnerResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.linkrunner.source import LinkrunnerSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert LinkrunnerSource().source_type == ExternalDataSourceType.LINKRUNNER++ def test_config_advertises_a_single_secret_api_key_field(self) -> None:+ config = LinkrunnerSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.ADVERTISING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/linkrunner"+ assert config.iconPath.endswith(".svg")+ assert [f.name for f in config.fields] == ["api_key"]+ api_key = config.fields[0]+ assert isinstance(api_key, SourceFieldInputConfig)+ assert api_key.type == SourceFieldInputConfigType.PASSWORD+ assert api_key.required is True+ assert api_key.secret is True+++class TestGetSchemas:+ @parameterized.expand(+ [+ # (endpoint, supports_incremental, primary_keys)+ ("campaigns", False, ["display_id"]),+ ("attributed_users", True, ["campaign_display_id", "user_id", "attributed_at"]),+ ("reporting_campaigns", False, ["display_id"]),+ ]+ )+ def test_schema_incremental_and_primary_keys(+ self, endpoint: str, supports_incremental: bool, primary_keys: list[str]+ ) -> None:+ schemas = {s.name: s for s in LinkrunnerSource().get_schemas(MagicMock(), team_id=1)}+ schema = schemas[endpoint]+ # Only attributed-users has a genuine server-side timestamp filter; the rest ship full refresh.+ assert schema.supports_incremental is supports_incremental+ assert schema.detected_primary_keys == primary_keys++ def test_names_filter_restricts_output(self) -> None:+ schemas = LinkrunnerSource().get_schemas(MagicMock(), team_id=1, names=["campaigns"])+ assert [s.name for s in schemas] == ["campaigns"]++ def test_documented_tables_render_without_credentials(self) -> None:+ # lists_tables_without_credentials=True lets the public docs render the table catalog with no I/O.+ tables = LinkrunnerSource().get_documented_tables()+ assert {t["name"] for t in tables} == {"campaigns", "attributed_users", "reporting_campaigns"}+++class TestValidateCredentials:+ @parameterized.expand([("valid", True, True), ("invalid", False, False)])+ def test_validation_maps_transport_result(self, _name: str, transport_ok: bool, expected: bool) -> None:+ config = MagicMock(api_key="key")+ with patch.object(source_module, "validate_linkrunner_credentials", return_value=transport_ok):+ ok, error = LinkrunnerSource().validate_credentials(config, team_id=1)+ assert ok is expected+ assert (error is None) is expected+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.linkrunner.io/api/v1/campaigns",+ True,+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.linkrunner.io/api/v1/attributed-users",+ True,+ ),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.linkrunner.io", False),+ ("timeout", "HTTPSConnectionPool(host='api.linkrunner.io', port=443): Read timed out.", False),+ ]+ )+ def test_only_credential_errors_are_non_retryable(self, _name: str, observed: str, expected: bool) -> None:+ non_retryable = LinkrunnerSource().get_non_retryable_errors()+ assert any(key in observed for key in non_retryable) is expected+++class TestPipelineWiring:+ def test_resumable_manager_bound_to_resume_config(self) -> None:+ inputs = MagicMock()+ manager = LinkrunnerSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LinkrunnerResumeConfig++ def test_source_for_pipeline_plumbs_incremental_inputs(self) -> None:+ config = MagicMock(api_key="key")+ inputs = MagicMock(+ schema_name="attributed_users",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field="attributed_at",+ )+ manager = MagicMock()+ with patch.object(source_module, "linkrunner_source") as mock_source:+ LinkrunnerSource().source_for_pipeline(config, manager, inputs)+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "attributed_users"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:+ config = MagicMock(api_key="key")+ inputs = MagicMock(+ schema_name="campaigns",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00Z",+ incremental_field=None,+ )+ with patch.object(source_module, "linkrunner_source") as mock_source:+ LinkrunnerSource().source_for_pipeline(config, MagicMock(), inputs)+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None+++def test_registered_in_source_registry() -> None:+ from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry++ sources = SourceRegistry.get_all_sources()+ assert ExternalDataSourceType.LINKRUNNER in sources+ assert sources[ExternalDataSourceType.LINKRUNNER].source_type == ExternalDataSourceType.LINKRUNNER