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(data-warehouse): add 7 missing LinkedIn Ads tables (#77278)

Tom Owers778f7268c317
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
index 0b9d6018b04c..18b5f6e2daa1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS.md
@@ -255,16 +255,18 @@ Two small additions would unblock most real analysis.
- [ ] Workflows.
- [ ] Web analytics events. `WEB_ANALYTICS_EVENTS_ENDPOINT` is already defined in `hubspot/settings.py:63` but is referenced nowhere else, so this is a half-finished thread rather than a new build.
-### LinkedIn Ads — needs confirmation
+### LinkedIn Ads — spec-verified
-Seven tables, and the only ad platform that already ships `creatives`.
+Spec: <https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/ads-reporting> (version 202607), diffed 2026-08-04.
-- [ ] Member-demographic pivots: `MEMBER_COMPANY`, `MEMBER_INDUSTRY`, `MEMBER_SENIORITY`, `MEMBER_JOB_TITLE`, `MEMBER_COUNTRY_V2`, `MEMBER_COMPANY_SIZE`. This is the reason people advertise on LinkedIn and none of it is available.
-- [ ] Lead gen forms and form responses.
-- [ ] Conversions and conversion events.
-- [ ] Audiences / DMP segments.
-- [ ] Budget and bid data on campaigns.
-- [ ] Video ad analytics.
+Have: `accounts`, `campaigns`, `campaign_groups`, `creatives`, `conversions`, `campaign_stats`, `campaign_group_stats`, `creative_stats`, `member_company_stats`, `member_company_size_stats`, `member_country_stats`, `member_industry_stats`, `member_job_title_stats`, `member_seniority_stats`. The only ad platform that ships `creatives`.
+
+- [x] Member-demographic pivots: `MEMBER_COMPANY`, `MEMBER_INDUSTRY`, `MEMBER_SENIORITY`, `MEMBER_JOB_TITLE`, `MEMBER_COUNTRY_V2`, `MEMBER_COMPANY_SIZE`. This is the reason people advertise on LinkedIn and none of it is available.
+- [ ] Lead gen forms and form responses. (skipped: the Lead Sync API needs `r_marketing_leadgen_automation`, which is not in PostHog's LinkedIn OAuth app and belongs to a separate approval program)
+- [x] Conversions and conversion events. (conversion rules ship as `conversions`; the conversion-tracking reference documents no read finder for individual conversion events, so conversion counts stay available through the `externalWebsiteConversions` metric on the stats tables)
+- [ ] Audiences / DMP segments. (skipped: `dmpSegments` needs `rw_dmp_segments`, part of the Audiences program and not granted with the Marketing API program)
+- [ ] Budget and bid data on campaigns. (skipped: `dailyBudget`, `unitCost` and `costType` already sync on `campaigns` and `totalBudget` on `campaign_groups`; the remainder would mean adding columns to live tables)
+- [ ] Video ad analytics. (skipped: `videoViews` and `videoCompletions` already sync on the stats tables; the extra quartile metrics would mean adding columns to live tables)
### Google Search Console — needs confirmation
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/canonical_descriptions.py
index 5d581f45cd85..b18c59b463fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/canonical_descriptions.py
@@ -30,6 +30,20 @@ _STATS_COLUMNS = {
"follows": "Number of new followers attributed to the ad.",
}
+# Professional demographic breakdowns carry the same metrics minus conversion value, which LinkedIn
+# only reports for non-demographic pivots.
+_DEMOGRAPHIC_STATS_COLUMNS = {
+ key: value for key, value in _STATS_COLUMNS.items() if key != "conversion_value_in_local_currency"
+}
+
+_DEMOGRAPHIC_DOCS_URL = "https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/ads-reporting"
+
+_DEMOGRAPHIC_CAVEAT = (
+ "LinkedIn approximates professional demographic metrics to protect member privacy: only the top "
+ "100 values per creative per day are returned, values with fewer than 3 events are dropped, and "
+ "the data is retained for two years."
+)
+
CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"accounts": {
@@ -121,4 +135,72 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"date_range": "The reporting date range these metrics cover.",
},
},
+ "conversions": {
+ "description": "A conversion rule defined on the ad account, describing an action on the advertiser's site that LinkedIn attributes back to ads.",
+ "docs_url": "https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads-reporting/conversion-tracking",
+ "columns": {
+ "id": "Unique identifier for the conversion rule.",
+ "name": "Short name for the rule, shown in Campaign Manager and in reports.",
+ "type": "What the member did (ADD_TO_CART, DOWNLOAD, INSTALL, KEY_PAGE_VIEW, LEAD, PURCHASE, SIGN_UP, OTHER).",
+ "enabled": "Whether the rule is currently able to record conversion events.",
+ "account_id": "ID of the ad account the conversion rule belongs to.",
+ "campaigns": "Campaign URNs the conversion rule is associated with.",
+ "attribution_type": "How conversions are counted: LAST_TOUCH_BY_CAMPAIGN (once per campaign) or LAST_TOUCH_BY_CONVERSION (once per conversion rule).",
+ "conversion_method": "How the conversion is recorded, for example via the LinkedIn Insight Tag or the Conversions API.",
+ "post_click_attribution_window_size": "Days after a click during which a conversion is still attributed, in days (1, 7 or 30).",
+ "view_through_attribution_window_size": "Days after an impression during which a conversion is still attributed, in days (1, 7 or 30).",
+ "value_amount": "Monetary value assigned to one conversion, as a decimal string.",
+ "value_currency_code": "Currency of the conversion value, matching the ad account's currency.",
+ "created_time": "Date the conversion rule was created.",
+ "last_modified_time": "Date the conversion rule was last modified.",
+ },
+ },
+ "member_company_stats": {
+ "description": f"Daily ad analytics broken down by the company members work at. {_DEMOGRAPHIC_CAVEAT}",
+ "docs_url": _DEMOGRAPHIC_DOCS_URL,
+ "columns": {
+ **_DEMOGRAPHIC_STATS_COLUMNS,
+ "pivot_value": "Organization URN of the member's company, for example urn:li:organization:1111. Results can include companies the campaign did not explicitly target.",
+ },
+ },
+ "member_company_size_stats": {
+ "description": f"Daily ad analytics broken down by the headcount band of the company members work at. {_DEMOGRAPHIC_CAVEAT}",
+ "docs_url": _DEMOGRAPHIC_DOCS_URL,
+ "columns": {
+ **_DEMOGRAPHIC_STATS_COLUMNS,
+ "pivot_value": "The company size band the metrics belong to, as LinkedIn returns it.",
+ },
+ },
+ "member_country_stats": {
+ "description": f"Daily ad analytics broken down by the country members are in. {_DEMOGRAPHIC_CAVEAT}",
+ "docs_url": _DEMOGRAPHIC_DOCS_URL,
+ "columns": {
+ **_DEMOGRAPHIC_STATS_COLUMNS,
+ "pivot_value": "Geo URN of the member's country, for example urn:li:geo:103644278. Resolve it with LinkedIn's Geo API.",
+ },
+ },
+ "member_industry_stats": {
+ "description": f"Daily ad analytics broken down by the industry members work in. {_DEMOGRAPHIC_CAVEAT}",
+ "docs_url": _DEMOGRAPHIC_DOCS_URL,
+ "columns": {
+ **_DEMOGRAPHIC_STATS_COLUMNS,
+ "pivot_value": "Industry URN of the member's industry, for example urn:li:industry:96. Resolve it with LinkedIn's Industries API.",
+ },
+ },
+ "member_job_title_stats": {
+ "description": f"Daily ad analytics broken down by member job title. {_DEMOGRAPHIC_CAVEAT}",
+ "docs_url": _DEMOGRAPHIC_DOCS_URL,
+ "columns": {
+ **_DEMOGRAPHIC_STATS_COLUMNS,
+ "pivot_value": "Title URN of the member's job title, for example urn:li:title:9. Resolve it with LinkedIn's Titles API.",
+ },
+ },
+ "member_seniority_stats": {
+ "description": f"Daily ad analytics broken down by member seniority. {_DEMOGRAPHIC_CAVEAT}",
+ "docs_url": _DEMOGRAPHIC_DOCS_URL,
+ "columns": {
+ **_DEMOGRAPHIC_STATS_COLUMNS,
+ "pivot_value": "Seniority URN of the member's seniority level, for example urn:li:seniority:6. Resolve it with LinkedIn's Seniorities API.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py
index 7cfead6d3bde..cf0f8aced7ce 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/client.py
@@ -20,9 +20,16 @@ from .schemas import (
logger = structlog.get_logger(__name__)
+# Inverse of LINKEDIN_ADS_PIVOTS — each analytics resource maps to exactly one pivot.
+RESOURCE_BY_PIVOT = {pivot: resource for resource, pivot in LINKEDIN_ADS_PIVOTS.items()}
+
LINKEDIN_SPONSORED_URN_PREFIX = "urn:li:sponsored"
MAX_PAGE_SIZE = 1000
CREATIVES_PAGE_SIZE = 100 # creatives backend returns transient 500s on heavier requests
+INDEX_PAGE_SIZE = 100
+# LinkedIn caps an ad account at 1000 conversion rules, so 100 pages is far past any real account
+# and only exists to stop a finder that ignores `start` from looping forever.
+MAX_INDEX_PAGES = 100
# Default LinkedIn Marketing API version header. Callers pass a resolved version through the
# source's version dispatch; this default backs the legacy `v1` pin and credential-probe paths.
API_VERSION = "202508"
@@ -178,6 +185,18 @@ class LinkedinAdsClient:
page_size=CREATIVES_PAGE_SIZE,
)
+ def get_conversions(self, account_id: str) -> Generator[tuple[list[dict[str, Any]], None]]:
+ """Conversion rules defined on the ad account. `q=account` paginates with Rest.li index
+ parameters (`start`/`count`) rather than the pageToken envelope the ad entity finders use,
+ so there is no token to resume from."""
+ account_urn = f"{LINKEDIN_SPONSORED_URN_PREFIX}Account:{account_id}"
+ yield from self._make_index_paginated_request(
+ endpoint=LinkedinAdsResource.Conversions,
+ path=f"/{LINKEDIN_ADS_ENDPOINTS[LinkedinAdsResource.Conversions]}",
+ finder="account",
+ extra_params={"account": account_urn},
+ )
+
def get_analytics(
self,
account_id: str,
@@ -191,12 +210,7 @@ class LinkedinAdsClient:
capped by LinkedIn — we can't tell which rows were dropped — so we discard it and re-fetch
the same start with a smaller window rather than yielding partial data. Only a single-day
window that still caps is surfaced (with a warning), since it can't be split further."""
- resource_by_pivot = {
- LinkedinAdsPivot.CAMPAIGN: LinkedinAdsResource.CampaignStats,
- LinkedinAdsPivot.CAMPAIGN_GROUP: LinkedinAdsResource.CampaignGroupStats,
- LinkedinAdsPivot.CREATIVE: LinkedinAdsResource.CreativeStats,
- }
- resource = resource_by_pivot.get(pivot, LinkedinAdsResource.CampaignStats)
+ resource = RESOURCE_BY_PIVOT.get(pivot, LinkedinAdsResource.CampaignStats)
fields = ",".join(self._get_fields_for_resource(resource))
accounts = [f"{LINKEDIN_SPONSORED_URN_PREFIX}Account:{account_id}"]
@@ -266,8 +280,8 @@ class LinkedinAdsClient:
"""Get data by resource, yielding each page and its nextPageToken (if any).
`starting_page_token` applies to the paginated entity endpoints (campaigns,
- campaign_groups, creatives) and is ignored for single-shot endpoints
- (accounts, analytics — analytics paginates by date-range chunking instead).
+ campaign_groups, creatives) and is ignored for endpoints that don't paginate by token
+ (accounts, conversions — index paginated; analytics — date-range chunked).
"""
if resource == LinkedinAdsResource.Accounts:
yield self.get_accounts(), None
@@ -277,6 +291,8 @@ class LinkedinAdsClient:
yield from self.get_campaign_groups(account_id, starting_page_token=starting_page_token)
elif resource == LinkedinAdsResource.Creatives:
yield from self.get_creatives(account_id, starting_page_token=starting_page_token)
+ elif resource == LinkedinAdsResource.Conversions:
+ yield from self.get_conversions(account_id)
elif resource in LINKEDIN_ADS_PIVOTS:
yield from self.get_analytics(account_id, LINKEDIN_ADS_PIVOTS[resource], date_start, date_end)
else:
@@ -395,6 +411,50 @@ class LinkedinAdsClient:
page_token = next_page_token
+ def _make_index_paginated_request(
+ self,
+ endpoint: LinkedinAdsResource,
+ path: str,
+ finder: str,
+ extra_params: Optional[dict[str, Any]] = None,
+ page_size: int = INDEX_PAGE_SIZE,
+ ) -> Generator[tuple[list[dict[str, Any]], None]]:
+ """Yield each page of a Rest.li index-paginated finder (`start` / `count`).
+
+ Yields `(elements, None)` to match the token-paginated signature; index offsets aren't
+ resumable across runs, so nothing is persisted. A short page means the last page — the
+ `total` in the paging envelope is optional, so we don't rely on it.
+ """
+ start = 0
+
+ for _ in range(MAX_INDEX_PAGES):
+ params: dict[str, Any] = {
+ "fields": ",".join(self._get_fields_for_resource(endpoint)),
+ "start": start,
+ "count": page_size,
+ }
+ if extra_params:
+ params.update(extra_params)
+
+ response = self._call_finder(resource_path=path, finder=finder, params=params)
+ elements = response.elements
+
+ if not elements:
+ return
+
+ yield elements, None
+
+ if len(elements) < page_size:
+ return
+
+ start += page_size
+
+ logger.warning(
+ "linkedin_ads.index_pagination_cap_reached",
+ endpoint=endpoint.value,
+ pages=MAX_INDEX_PAGES,
+ )
+
def _format_date_range(self, date_start: str, date_end: str) -> dict:
"""Format date range for LinkedIn API as structured object."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
index 75c28d6f0057..23648aeed7ed 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/linkedin_ads.py
@@ -26,7 +26,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.types import IncrementalFieldType
from .client import API_VERSION, LinkedinAdsClient, LinkedinAdsDailyRateLimitError, LinkedinAdsResource
-from .schemas import FLOAT_FIELDS, INT_FIELDS, RESOURCE_SCHEMAS, URN_COLUMNS, VIRTUAL_COLUMN_URN_MAPPING
+from .schemas import (
+ EPOCH_MS_VIRTUAL_COLUMNS,
+ FLOAT_FIELDS,
+ INT_FIELDS,
+ RESOURCE_SCHEMAS,
+ URN_COLUMNS,
+ VIRTUAL_COLUMN_URN_MAPPING,
+)
module_logger = structlog.get_logger(__name__)
@@ -67,6 +74,9 @@ class LinkedinAdsSchema:
is_stats: bool
partition_size: int
filter_field_names: list[tuple[str, IncrementalFieldType]] | None = None
+ pivot_value_column: str | None = None
+ initial_lookback_days: int | None = None
+ should_sync_default: bool = True
def get_incremental_fields() -> dict[str, list[tuple[str, IncrementalFieldType]]]:
@@ -114,6 +124,9 @@ def get_schemas() -> dict[str, LinkedinAdsSchema]:
is_stats=is_stats,
filter_field_names=filter_field_names,
partition_size=partition_size,
+ pivot_value_column=resource_contents.get("pivot_value_column", None),
+ initial_lookback_days=resource_contents.get("initial_lookback_days", None),
+ should_sync_default=resource_contents.get("should_sync_default", True),
)
schemas[resource_name] = schema
@@ -211,7 +224,8 @@ def linkedin_ads_source(
now = dt.datetime.now()
date_start = None
date_end = now.strftime("%Y-%m-%d")
- default_start = (now - dt.timedelta(days=INITIAL_ANALYTICS_LOOKBACK_DAYS)).strftime("%Y-%m-%d")
+ lookback_days = schema.initial_lookback_days or INITIAL_ANALYTICS_LOOKBACK_DAYS
+ default_start = (now - dt.timedelta(days=lookback_days)).strftime("%Y-%m-%d")
if should_use_incremental_field and schema.filter_field_names:
if incremental_field is None or incremental_field_type is None:
@@ -384,14 +398,25 @@ def _flatten_linkedin_record(
flattened["created_time"] = created_time
flattened["last_modified_time"] = last_modified_time
- elif field_name in ("createdAt", "lastModifiedAt"):
+ elif field_name in EPOCH_MS_VIRTUAL_COLUMNS:
timestamp_ms = record.get(field_name)
- virtual_name = "created_time" if field_name == "createdAt" else "last_modified_time"
+ virtual_name = EPOCH_MS_VIRTUAL_COLUMNS[field_name]
if isinstance(timestamp_ms, int):
flattened[virtual_name] = dt.datetime.fromtimestamp(timestamp_ms / 1000, tz=dt.UTC).date()
else:
flattened[virtual_name] = None
+ elif field_name == "value":
+ # Conversion value arrives as {"amount": "10", "currencyCode": "USD"}; split it so the
+ # amount is queryable without unpacking a struct.
+ conversion_value = record.get("value")
+ if isinstance(conversion_value, dict):
+ flattened["value_amount"] = conversion_value.get("amount")
+ flattened["value_currency_code"] = conversion_value.get("currencyCode")
+ else:
+ flattened["value_amount"] = None
+ flattened["value_currency_code"] = None
+
elif field_name in URN_COLUMNS:
urn_value = record.get(field_name)
extracted_id: int | None = None
@@ -408,6 +433,15 @@ def _flatten_linkedin_record(
# Handle virtual columns that derive from pivot values
if field_name == "pivotValues":
+ if schema.pivot_value_column:
+ # Professional demographic pivots return URNs we have no local table to join
+ # against (`urn:li:industry:96`), and MEMBER_COMPANY_SIZE returns a named bucket
+ # rather than a numeric id, so keep the value verbatim.
+ flattened[schema.pivot_value_column] = next(
+ (value for value in record.get("pivotValues", []) if isinstance(value, str) and value),
+ None,
+ )
+
for pivot_value in record.get("pivotValues", []):
if isinstance(pivot_value, str):
pivot_result = _extract_type_and_id_from_urn(pivot_value)
@@ -449,4 +483,10 @@ def _flatten_linkedin_record(
module_logger.warning("linkedin_ads.missing_stats_date_range", resource=schema.name)
return None
+ # Same exposure for the demographic pivot column: it's the third primary key component, and a
+ # row without it can't identify which demographic value the metrics belong to.
+ if schema.pivot_value_column and flattened.get(schema.pivot_value_column) is None:
+ module_logger.warning("linkedin_ads.missing_pivot_value", resource=schema.name)
+ return None
+
return flattened
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/schemas.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/schemas.py
index c02d124ffe88..be0317bfe30e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/schemas.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/schemas.py
@@ -26,6 +26,16 @@ INT_FIELDS = {
# There are in the results from the API. The value is in the URN format.
URN_COLUMNS = ["campaignGroup", "account", "campaign", "creative"]
+# Fields LinkedIn returns as epoch-millisecond longs, and the date column each one flattens into.
+# The ad entity finders use `createdAt`/`lastModifiedAt`; the conversions finder uses the shorter
+# `created`/`lastModified` names for the same thing.
+EPOCH_MS_VIRTUAL_COLUMNS = {
+ "createdAt": "created_time",
+ "lastModifiedAt": "last_modified_time",
+ "created": "created_time",
+ "lastModified": "last_modified_time",
+}
+
# This maps the the URN type to the virtual column name. LinkedIn Ads API uses URNs to identify resources.
# URNs are like "urn:li:sponsoredCampaign:12345678"
VIRTUAL_COLUMN_URN_MAPPING = {
@@ -41,9 +51,16 @@ class LinkedinAdsResource(StrEnum):
Campaigns = "campaigns"
CampaignGroups = "campaign_groups"
Creatives = "creatives"
+ Conversions = "conversions"
CampaignStats = "campaign_stats"
CampaignGroupStats = "campaign_group_stats"
CreativeStats = "creative_stats"
+ MemberCompanyStats = "member_company_stats"
+ MemberCompanySizeStats = "member_company_size_stats"
+ MemberCountryStats = "member_country_stats"
+ MemberIndustryStats = "member_industry_stats"
+ MemberJobTitleStats = "member_job_title_stats"
+ MemberSeniorityStats = "member_seniority_stats"
class LinkedinAdsPivot(StrEnum):
@@ -51,6 +68,12 @@ class LinkedinAdsPivot(StrEnum):
CAMPAIGN = "CAMPAIGN"
CAMPAIGN_GROUP = "CAMPAIGN_GROUP"
CREATIVE = "CREATIVE"
+ MEMBER_COMPANY = "MEMBER_COMPANY"
+ MEMBER_COMPANY_SIZE = "MEMBER_COMPANY_SIZE"
+ MEMBER_COUNTRY_V2 = "MEMBER_COUNTRY_V2"
+ MEMBER_INDUSTRY = "MEMBER_INDUSTRY"
+ MEMBER_JOB_TITLE = "MEMBER_JOB_TITLE"
+ MEMBER_SENIORITY = "MEMBER_SENIORITY"
# LinkedIn API endpoint mappings
@@ -59,9 +82,16 @@ LINKEDIN_ADS_ENDPOINTS = {
LinkedinAdsResource.Campaigns: "adCampaigns",
LinkedinAdsResource.CampaignGroups: "adCampaignGroups",
LinkedinAdsResource.Creatives: "creatives",
+ LinkedinAdsResource.Conversions: "conversions",
LinkedinAdsResource.CampaignStats: "adAnalytics",
LinkedinAdsResource.CampaignGroupStats: "adAnalytics",
LinkedinAdsResource.CreativeStats: "adAnalytics",
+ LinkedinAdsResource.MemberCompanyStats: "adAnalytics",
+ LinkedinAdsResource.MemberCompanySizeStats: "adAnalytics",
+ LinkedinAdsResource.MemberCountryStats: "adAnalytics",
+ LinkedinAdsResource.MemberIndustryStats: "adAnalytics",
+ LinkedinAdsResource.MemberJobTitleStats: "adAnalytics",
+ LinkedinAdsResource.MemberSeniorityStats: "adAnalytics",
}
# Pivot mappings for analytics resources
@@ -69,6 +99,12 @@ LINKEDIN_ADS_PIVOTS = {
LinkedinAdsResource.CampaignStats: LinkedinAdsPivot.CAMPAIGN,
LinkedinAdsResource.CampaignGroupStats: LinkedinAdsPivot.CAMPAIGN_GROUP,
LinkedinAdsResource.CreativeStats: LinkedinAdsPivot.CREATIVE,
+ LinkedinAdsResource.MemberCompanyStats: LinkedinAdsPivot.MEMBER_COMPANY,
+ LinkedinAdsResource.MemberCompanySizeStats: LinkedinAdsPivot.MEMBER_COMPANY_SIZE,
+ LinkedinAdsResource.MemberCountryStats: LinkedinAdsPivot.MEMBER_COUNTRY_V2,
+ LinkedinAdsResource.MemberIndustryStats: LinkedinAdsPivot.MEMBER_INDUSTRY,
+ LinkedinAdsResource.MemberJobTitleStats: LinkedinAdsPivot.MEMBER_JOB_TITLE,
+ LinkedinAdsResource.MemberSeniorityStats: LinkedinAdsPivot.MEMBER_SENIORITY,
}
@@ -82,6 +118,64 @@ class ResourceSchema(TypedDict):
partition_format: Literal["month", "week", "day"] | None
partition_size: int
is_stats: bool
+ # Column the raw first entry of `pivotValues` is written to, for pivots whose value is not a
+ # sponsored-entity URN we already flatten into an `*_id` column (the professional demographic
+ # pivots). Doubles as part of the primary key for those tables.
+ pivot_value_column: NotRequired[str]
+ # Overrides the source-wide initial analytics lookback for resources with shorter retention.
+ initial_lookback_days: NotRequired[int]
+ # False leaves the table unticked in the schema picker.
+ should_sync_default: NotRequired[bool]
+
+
+# LinkedIn retains professional demographic reporting for two years, versus ten for performance
+# reporting, and rejects a start date outside the retention window with a 400 (DATE_TOO_EARLY).
+DEMOGRAPHIC_RETENTION_DAYS = 365 * 2
+
+# Metrics requested for a professional demographic pivot. Same list as the performance stats
+# resources minus `conversionValueInLocalCurrency`, which LinkedIn documents as available for
+# non-demographic pivots only.
+DEMOGRAPHIC_STATS_FIELD_NAMES = [
+ "impressions",
+ "clicks",
+ "dateRange",
+ "pivotValues",
+ "costInUsd",
+ "costInLocalCurrency",
+ "externalWebsiteConversions",
+ "landingPageClicks",
+ "totalEngagements",
+ "videoViews",
+ "videoCompletions",
+ "oneClickLeads",
+ "follows",
+]
+
+# Column holding the raw demographic pivot URN (e.g. `urn:li:industry:96`). Kept as the raw string
+# because the id segment is only numeric for some pivots — MEMBER_COMPANY_SIZE returns a named
+# size bucket — and there is no table in this source to join a parsed id against.
+DEMOGRAPHIC_PIVOT_COLUMN = "pivot_value"
+
+
+def _demographic_stats_schema(resource_name: str) -> "ResourceSchema":
+ return {
+ "resource_name": resource_name,
+ "field_names": DEMOGRAPHIC_STATS_FIELD_NAMES.copy(),
+ "primary_key": ["date_start", "date_end", DEMOGRAPHIC_PIVOT_COLUMN],
+ "filter_field_names": [
+ ("date_start", IncrementalFieldType.Date),
+ ],
+ "partition_keys": ["date_start"],
+ "partition_mode": "datetime",
+ "partition_format": "week",
+ "is_stats": True,
+ "partition_size": 1,
+ "pivot_value_column": DEMOGRAPHIC_PIVOT_COLUMN,
+ "initial_lookback_days": DEMOGRAPHIC_RETENTION_DAYS,
+ # One row per (day × demographic value) on top of the performance tables, and only useful
+ # to advertisers who report on audience makeup, so it stays off unless asked for.
+ "should_sync_default": False,
+ }
# LinkedIn Ads resource schemas
@@ -160,6 +254,30 @@ RESOURCE_SCHEMAS: dict[LinkedinAdsResource, ResourceSchema] = {
"is_stats": False,
"partition_size": 1,
},
+ LinkedinAdsResource.Conversions: {
+ "resource_name": "conversions",
+ "field_names": [
+ "id",
+ "name",
+ "type",
+ "enabled",
+ "account",
+ "campaigns",
+ "attributionType",
+ "conversionMethod",
+ "postClickAttributionWindowSize",
+ "viewThroughAttributionWindowSize",
+ "value",
+ "created",
+ "lastModified",
+ ],
+ "primary_key": ["id"],
+ "partition_keys": ["created_time"],
+ "partition_mode": "datetime",
+ "partition_format": "week",
+ "is_stats": False,
+ "partition_size": 1,
+ },
LinkedinAdsResource.CampaignStats: {
"resource_name": "campaign_stats",
"field_names": [
@@ -244,4 +362,10 @@ RESOURCE_SCHEMAS: dict[LinkedinAdsResource, ResourceSchema] = {
"is_stats": True,
"partition_size": 1,
},
+ LinkedinAdsResource.MemberCompanyStats: _demographic_stats_schema("member_company_stats"),
+ LinkedinAdsResource.MemberCompanySizeStats: _demographic_stats_schema("member_company_size_stats"),
+ LinkedinAdsResource.MemberCountryStats: _demographic_stats_schema("member_country_stats"),
+ LinkedinAdsResource.MemberIndustryStats: _demographic_stats_schema("member_industry_stats"),
+ LinkedinAdsResource.MemberJobTitleStats: _demographic_stats_schema("member_job_title_stats"),
+ LinkedinAdsResource.MemberSeniorityStats: _demographic_stats_schema("member_seniority_stats"),
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py
index 2d6554ecfeb6..06535e60198b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/source.py
@@ -264,8 +264,9 @@ class LinkedInAdsSource(ResumableSource[LinkedinAdsSourceConfig, LinkedInAdsResu
{"label": column_name, "type": column_type, "field": column_name, "field_type": column_type}
for column_name, column_type in ads_incremental_fields.get(endpoint, [])
],
+ should_sync_default=schema.should_sync_default,
)
- for endpoint in linkedin_ads_schemas.keys()
+ for endpoint, schema in linkedin_ads_schemas.items()
]
if names is not None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
index 02ec5425b2e8..0d05e61e6059 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_ads.py
@@ -33,10 +33,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_a
_extract_type_and_id_from_urn,
_flatten_linkedin_record,
_get_integration,
+ get_schemas,
linkedin_ads_client,
linkedin_ads_source,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.schemas import (
+ DEMOGRAPHIC_RETENTION_DAYS,
FLOAT_FIELDS,
INT_FIELDS,
)
@@ -1042,3 +1044,148 @@ class TestLinkedinAdsSource:
list(items)
assert mock_client.get_data_by_resource.call_args[1]["date_start"] == "2024-01-01"
+
+
+class TestDemographicStatsFlattening:
+ @pytest.mark.parametrize(
+ "resource_name,pivot_value",
+ [
+ ("member_company_stats", "urn:li:organization:1111"),
+ # MEMBER_COMPANY_SIZE is the one demographic pivot whose value isn't a URN, so an
+ # id-parsing shortcut would silently drop every row on this table.
+ ("member_company_size_stats", "SIZE_11_TO_50"),
+ ("member_country_stats", "urn:li:geo:103644278"),
+ ("member_industry_stats", "urn:li:industry:96"),
+ ("member_job_title_stats", "urn:li:title:9"),
+ ("member_seniority_stats", "urn:li:seniority:6"),
+ ],
+ )
+ def test_pivot_value_is_kept_verbatim(self, resource_name: str, pivot_value: str):
+ schema = get_schemas()[resource_name]
+
+ flattened = _flatten_linkedin_record(
+ {
+ "impressions": 6,
+ "pivotValues": [pivot_value],
+ "dateRange": {
+ "start": {"year": 2024, "month": 5, "day": 28},
+ "end": {"year": 2024, "month": 5, "day": 28},
+ },
+ },
+ schema,
+ )
+
+ assert flattened is not None
+ assert flattened["pivot_value"] == pivot_value
+ assert flattened["date_start"] == dt.date(2024, 5, 28)
+ assert schema.primary_keys == ["date_start", "date_end", "pivot_value"]
+
+ @pytest.mark.parametrize("pivot_values", [[], [None], [""]])
+ def test_row_without_a_pivot_value_is_dropped(self, pivot_values: list):
+ schema = get_schemas()["member_industry_stats"]
+
+ flattened = _flatten_linkedin_record(
+ {
+ "impressions": 6,
+ "pivotValues": pivot_values,
+ "dateRange": {
+ "start": {"year": 2024, "month": 5, "day": 28},
+ "end": {"year": 2024, "month": 5, "day": 28},
+ },
+ },
+ schema,
+ )
+
+ assert flattened is None
+
+ def test_performance_stats_keep_their_entity_id_columns(self):
+ schema = get_schemas()["campaign_stats"]
+
+ flattened = _flatten_linkedin_record(
+ {
+ "impressions": 6,
+ "pivotValues": ["urn:li:sponsoredCampaign:123"],
+ "dateRange": {
+ "start": {"year": 2024, "month": 5, "day": 28},
+ "end": {"year": 2024, "month": 5, "day": 28},
+ },
+ },
+ schema,
+ )
+
+ assert flattened is not None
+ assert flattened["campaign_id"] == 123
+ assert "pivot_value" not in flattened
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.linkedin_ads.linkedin_ads_client"
+ )
+ def test_first_sync_stays_within_the_demographic_retention_window(self, mock_client_func):
+ mock_client = mock.MagicMock()
+ mock_client.get_data_by_resource.return_value = [([], None)]
+ mock_client_func.return_value = mock_client
+
+ result = linkedin_ads_source(
+ config=LinkedinAdsSourceConfig(linkedin_ads_integration_id=123, account_id="456"),
+ resource_name="member_industry_stats",
+ team_id=789,
+ resumable_source_manager=_make_resume_manager(),
+ logger=mock.MagicMock(),
+ should_use_incremental_field=True,
+ incremental_field="date_start",
+ incremental_field_type=IncrementalFieldType.Date,
+ db_incremental_field_last_value=None,
+ )
+
+ items = result.items()
+ assert isinstance(items, Iterable)
+ list(items)
+
+ date_start = dt.date.fromisoformat(mock_client.get_data_by_resource.call_args[1]["date_start"])
+ expected_floor = (dt.datetime.now() - dt.timedelta(days=DEMOGRAPHIC_RETENTION_DAYS)).date()
+ assert abs((date_start - expected_floor).days) <= 1
+ assert DEMOGRAPHIC_RETENTION_DAYS < INITIAL_ANALYTICS_LOOKBACK_DAYS
+
+
+class TestConversionsFlattening:
+ def test_conversion_record_flattens_to_queryable_columns(self):
+ schema = get_schemas()["conversions"]
+
+ flattened = _flatten_linkedin_record(
+ {
+ "id": 104012,
+ "name": "Signup",
+ "type": "SIGN_UP",
+ "enabled": True,
+ "account": "urn:li:sponsoredAccount:519072844",
+ "campaigns": ["urn:li:sponsoredCampaign:345396555"],
+ "attributionType": "LAST_TOUCH_BY_CAMPAIGN",
+ "postClickAttributionWindowSize": 30,
+ "viewThroughAttributionWindowSize": 7,
+ "value": {"amount": "10", "currencyCode": "USD"},
+ "created": 1563230311551,
+ "lastModified": 1563230411551,
+ },
+ schema,
+ )
+
+ assert flattened is not None
+ assert flattened["id"] == 104012
+ assert flattened["account_id"] == 519072844
+ assert flattened["value_amount"] == "10"
+ assert flattened["value_currency_code"] == "USD"
+ # `created_time` is the partition key, so it has to survive the epoch-ms conversion.
+ assert flattened["created_time"] == dt.date(2019, 7, 15)
+ assert flattened["last_modified_time"] == dt.date(2019, 7, 15)
+
+ def test_conversion_without_a_monetary_value_keeps_stable_columns(self):
+ schema = get_schemas()["conversions"]
+
+ flattened = _flatten_linkedin_record(
+ {"id": 104012, "name": "Signup", "created": 1563230311551},
+ schema,
+ )
+
+ assert flattened is not None
+ assert flattened["value_amount"] is None
+ assert flattened["value_currency_code"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py
index 1e22f31aac4c..e2c13ab82080 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_client.py
@@ -9,9 +9,12 @@ from linkedin_api.common.errors import ResponseFormattingError
from structlog.testing import capture_logs
from products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client import (
+ INDEX_PAGE_SIZE,
+ MAX_INDEX_PAGES,
LinkedinAdsClient,
LinkedinAdsDailyRateLimitError,
LinkedinAdsPivot,
+ LinkedinAdsResource,
LinkedinAdsRetryableError,
)
@@ -560,6 +563,114 @@ class TestLinkedinAdsClient:
assert issubclass(LinkedinAdsRetryableError, Exception)
assert issubclass(LinkedinAdsDailyRateLimitError, Exception)
+ @pytest.mark.parametrize(
+ "resource,expected_pivot",
+ [
+ (LinkedinAdsResource.CampaignStats, "CAMPAIGN"),
+ (LinkedinAdsResource.CampaignGroupStats, "CAMPAIGN_GROUP"),
+ (LinkedinAdsResource.CreativeStats, "CREATIVE"),
+ (LinkedinAdsResource.MemberCompanyStats, "MEMBER_COMPANY"),
+ (LinkedinAdsResource.MemberCompanySizeStats, "MEMBER_COMPANY_SIZE"),
+ (LinkedinAdsResource.MemberCountryStats, "MEMBER_COUNTRY_V2"),
+ (LinkedinAdsResource.MemberIndustryStats, "MEMBER_INDUSTRY"),
+ (LinkedinAdsResource.MemberJobTitleStats, "MEMBER_JOB_TITLE"),
+ (LinkedinAdsResource.MemberSeniorityStats, "MEMBER_SENIORITY"),
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client.RestliClient")
+ def test_analytics_resource_requests_its_own_pivot(self, mock_restli_client, resource, expected_pivot):
+ mock_response = mock.MagicMock()
+ mock_response.status_code = 200
+ mock_response.elements = []
+
+ mock_client_instance = mock_restli_client.return_value
+ mock_client_instance.finder.return_value = mock_response
+
+ client = LinkedinAdsClient(self.access_token)
+ list(
+ client.get_data_by_resource(
+ resource=resource,
+ account_id=self.account_id,
+ date_start="2024-01-01",
+ date_end="2024-01-02",
+ )
+ )
+
+ assert mock_client_instance.finder.call_args[1]["query_params"]["pivot"] == expected_pivot
+
+ @pytest.mark.parametrize(
+ "resource",
+ [
+ LinkedinAdsResource.MemberCompanyStats,
+ LinkedinAdsResource.MemberCompanySizeStats,
+ LinkedinAdsResource.MemberCountryStats,
+ LinkedinAdsResource.MemberIndustryStats,
+ LinkedinAdsResource.MemberJobTitleStats,
+ LinkedinAdsResource.MemberSeniorityStats,
+ ],
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client.RestliClient")
+ def test_demographic_pivots_do_not_request_conversion_value(self, mock_restli_client, resource):
+ mock_response = mock.MagicMock()
+ mock_response.status_code = 200
+ mock_response.elements = []
+
+ mock_client_instance = mock_restli_client.return_value
+ mock_client_instance.finder.return_value = mock_response
+
+ client = LinkedinAdsClient(self.access_token)
+ list(
+ client.get_data_by_resource(
+ resource=resource,
+ account_id=self.account_id,
+ date_start="2024-01-01",
+ date_end="2024-01-02",
+ )
+ )
+
+ requested_fields = mock_client_instance.finder.call_args[1]["query_params"]["fields"].split(",")
+ assert "conversionValueInLocalCurrency" not in requested_fields
+ assert "pivotValues" in requested_fields
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client.RestliClient")
+ def test_get_conversions_walks_index_pages_until_short_page(self, mock_restli_client):
+ full_page = [{"id": index} for index in range(INDEX_PAGE_SIZE)]
+ last_page = [{"id": 9001}]
+
+ first_response = mock.MagicMock(status_code=200, elements=full_page)
+ second_response = mock.MagicMock(status_code=200, elements=last_page)
+
+ mock_client_instance = mock_restli_client.return_value
+ mock_client_instance.finder.side_effect = [first_response, second_response]
+
+ client = LinkedinAdsClient(self.access_token)
+ pages = list(client.get_conversions(self.account_id))
+
+ assert [elements for elements, _ in pages] == [full_page, last_page]
+ assert all(next_page_token is None for _, next_page_token in pages)
+
+ first_params = mock_client_instance.finder.call_args_list[0][1]["query_params"]
+ second_params = mock_client_instance.finder.call_args_list[1][1]["query_params"]
+ assert first_params["account"] == f"urn:li:sponsoredAccount:{self.account_id}"
+ assert (first_params["start"], first_params["count"]) == (0, INDEX_PAGE_SIZE)
+ assert second_params["start"] == INDEX_PAGE_SIZE
+ assert mock_client_instance.finder.call_args_list[0][1]["finder_name"] == "account"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linkedin_ads.client.RestliClient")
+ def test_get_conversions_stops_when_finder_ignores_offset(self, mock_restli_client):
+ mock_response = mock.MagicMock(status_code=200, elements=[{"id": index} for index in range(INDEX_PAGE_SIZE)])
+
+ mock_client_instance = mock_restli_client.return_value
+ mock_client_instance.finder.return_value = mock_response
+
+ client = LinkedinAdsClient(self.access_token)
+
+ with capture_logs() as logs:
+ pages = list(client.get_conversions(self.account_id))
+
+ assert len(pages) == MAX_INDEX_PAGES
+ assert any(entry["event"] == "linkedin_ads.index_pagination_cap_reached" for entry in logs)
+
def _status_response(status_code: int, text: str) -> mock.MagicMock:
response = mock.MagicMock()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py
index 875a6bb44554..8549ec00e104 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linkedin_ads/tests/test_linkedin_source.py
@@ -120,6 +120,26 @@ class TestLinkedInAdsSource:
assert mock_client_for_integration.call_args.kwargs["api_version"] == "202607"
+ def test_demographic_breakdowns_are_offered_but_not_enabled_by_default(self):
+ # These fan out to one row per day per demographic value on top of the performance tables,
+ # so auto-enabling them would multiply every existing connection's sync cost.
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ demographic_tables = [name for name in schemas if name.startswith("member_")]
+ assert sorted(demographic_tables) == [
+ "member_company_size_stats",
+ "member_company_stats",
+ "member_country_stats",
+ "member_industry_stats",
+ "member_job_title_stats",
+ "member_seniority_stats",
+ ]
+ assert all(not schemas[name].should_sync_default for name in demographic_tables)
+ assert all(schemas[name].supports_incremental for name in demographic_tables)
+
+ for name in ("accounts", "campaigns", "campaign_groups", "creatives", "conversions"):
+ assert schemas[name].should_sync_default
+
def test_validate_credentials_missing_account_id(self):
"""Test credential validation with missing account ID."""
invalid_config = LinkedinAdsSourceConfig(linkedin_ads_integration_id=456, account_id="")