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.

fix(marketing-analytics): don't tell people to connect ad accounts they don't run (#83218)

Javier Bahamondes3ac9383d8863
diff --git a/products/marketing_analytics/backend/api.py b/products/marketing_analytics/backend/api.py
index d2604709e659..d401507559aa 100644
--- a/products/marketing_analytics/backend/api.py
+++ b/products/marketing_analytics/backend/api.py
@@ -712,6 +712,18 @@ class AttributionHealthEntrySerializer(serializers.Serializer):
sample_unmatched_utm_sources = UnmatchedUtmSampleSerializer(
many=True, help_text="Sample of likely-yours unmatched utm_source values"
)
+ events_matched_paid_last_7d = serializers.IntegerField(
+ help_text=(
+ "Of the matched events, how many look paid: a cost-bearing utm_medium (cpc, cpm, cpv, cpa, ppc, "
+ "retargeting, or anything starting with 'paid') or a gclid/gad_source click id."
+ )
+ )
+ events_matched_tagged_medium_last_7d = serializers.IntegerField(
+ help_text=(
+ "Of the matched events, how many carry any utm_medium. Zero paid with a non-zero count here means "
+ "the traffic is tagged and organic; both zero means the team doesn't tag medium, which says nothing."
+ )
+ )
class IntegrationDiagnosticSerializer(serializers.Serializer):
diff --git a/products/marketing_analytics/backend/services/attribution_health.py b/products/marketing_analytics/backend/services/attribution_health.py
index 9d2cfe984995..1ccf7e0acba3 100644
--- a/products/marketing_analytics/backend/services/attribution_health.py
+++ b/products/marketing_analytics/backend/services/attribution_health.py
@@ -18,6 +18,7 @@ from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.dataclasses import frozen
from posthog.models.team.team import Team
from posthog.sync import database_sync_to_async
@@ -63,7 +64,7 @@ class UnmatchedUtmSample:
suggested_integration: NativeIntegration | None
-@dataclass
+@frozen
class AttributionHealthEntry:
integration_key: NativeIntegration
display_name: str
@@ -73,6 +74,11 @@ class AttributionHealthEntry:
last_event_with_matching_utm_at: datetime | None
matched_pct: float
sample_unmatched_utm_sources: list[UnmatchedUtmSample] = field(default_factory=list)
+ # Of the matched events, how many look paid, and how many carry any utm_medium.
+ # `paid == 0 and tagged > 0` is positive evidence the traffic is organic; both
+ # zero only means the team doesn't tag medium, which says nothing either way.
+ events_matched_paid_last_7d: int = 0
+ events_matched_tagged_medium_last_7d: int = 0
@dataclass
@@ -169,6 +175,10 @@ async def get_attribution_health(
acc = per_integration.get(matched_key)
if acc is not None:
acc.matched_count += count
+ acc.paid_count += row.paid_event_count
+ if matched_key == "google_ads":
+ acc.paid_count += row.google_click_id_count
+ acc.tagged_medium_count += row.tagged_medium_count
candidates = [d for d in (acc.last_matched_at, last_at) if d is not None]
acc.last_matched_at = max(candidates) if candidates else None
continue
@@ -203,17 +213,30 @@ async def get_attribution_health(
)
-@dataclass
+@frozen
class _UtmRow:
raw_utm_source: str
event_count: int
last_seen_at: datetime | None
-
-
-@dataclass
+ # A cost-bearing utm_medium, per PostHog's own channel-type rule
+ # (posthog.com/docs/data/channel-type). Platform-agnostic: any source can be paid.
+ paid_event_count: int = 0
+ # Counted apart from the medium, because `gclid` and `gad_source` name Google Ads
+ # specifically. They ride along on whatever URL carries them, so a link shared with a
+ # stale gclid would otherwise mark LinkedIn traffic as paid LinkedIn.
+ google_click_id_count: int = 0
+ # Events carrying any utm_medium at all. Separates "tagged, and organic" from
+ # "not tagged", which are different answers to "is this paid?".
+ tagged_medium_count: int = 0
+
+
+# Mutable by design: one instance per integration, summed across the utm rows.
+@dataclass(frozen=False)
class _IntegrationAccumulator:
key: NativeIntegration
matched_count: int = 0
+ paid_count: int = 0
+ tagged_medium_count: int = 0
likely_yours_count: int = 0
last_matched_at: datetime | None = None
likely_yours_samples: list[UnmatchedUtmSample] = field(default_factory=list)
@@ -235,6 +258,8 @@ class _IntegrationAccumulator:
last_event_with_matching_utm_at=self.last_matched_at,
matched_pct=matched_pct,
sample_unmatched_utm_sources=self.likely_yours_samples[:MAX_SAMPLE_UNMATCHED],
+ events_matched_paid_last_7d=self.paid_count,
+ events_matched_tagged_medium_last_7d=self.tagged_medium_count,
)
@@ -259,7 +284,16 @@ def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:
SELECT
lower(trim(properties.utm_source)) AS raw_utm_source,
count() AS event_count,
- max(timestamp) AS last_seen_at
+ max(timestamp) AS last_seen_at,
+ countIf(
+ lower(trim(properties.utm_medium)) IN ('cpc', 'cpm', 'cpv', 'cpa', 'ppc', 'retargeting')
+ OR startsWith(lower(trim(properties.utm_medium)), 'paid')
+ ) AS paid_event_count,
+ countIf(
+ (properties.gclid IS NOT NULL AND properties.gclid != '')
+ OR (properties.gad_source IS NOT NULL AND properties.gad_source != '')
+ ) AS google_click_id_count,
+ countIf(properties.utm_medium IS NOT NULL AND trim(properties.utm_medium) != '') AS tagged_medium_count
FROM events
WHERE
timestamp >= {since}
@@ -280,7 +314,14 @@ def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:
)
rows: list[_UtmRow] = []
for row in result.results or []:
- raw, count, last_at = row[0], row[1], row[2]
+ raw, count, last_at, paid_count, click_id_count, tagged_count = (
+ row[0],
+ row[1],
+ row[2],
+ row[3],
+ row[4],
+ row[5],
+ )
if not raw:
continue
rows.append(
@@ -288,6 +329,9 @@ def _fetch_utm_groups(team: Team, *, lookback_days: int) -> list[_UtmRow]:
raw_utm_source=cast(str, raw),
event_count=int(count or 0),
last_seen_at=last_at if isinstance(last_at, datetime) else None,
+ paid_event_count=int(paid_count or 0),
+ google_click_id_count=int(click_id_count or 0),
+ tagged_medium_count=int(tagged_count or 0),
)
)
return rows
diff --git a/products/marketing_analytics/backend/services/setup_plan.py b/products/marketing_analytics/backend/services/setup_plan.py
index 248d336d5c74..92af92099f5a 100644
--- a/products/marketing_analytics/backend/services/setup_plan.py
+++ b/products/marketing_analytics/backend/services/setup_plan.py
@@ -291,6 +291,20 @@ def _integration_suggestion(integration: IntegrationDiagnostic) -> Suggestion |
)
if status == "events_only":
+ # `utm_source` alone doesn't mean paid — `google` also covers gmail links and
+ # `linkedin` organic posts, so this fired "connect an ad account you don't
+ # have" at error severity. Suppressed only on positive evidence: most of the
+ # traffic carries a medium and none of it is paid. An untagged event is absence
+ # of evidence, not evidence of organic, so a tagged minority doesn't get to
+ # speak for it — a team that tags its posts but not its ad links still gets asked.
+ attr = integration.attribution
+ if (
+ attr is not None
+ and attr.events_matched_paid_last_7d == 0
+ and attr.events_matched_tagged_medium_last_7d * 2 > attr.events_matched_last_7d
+ ):
+ return None
+
# Traffic arrives but no spend data, so cost, ROAS and CAC are all unavailable.
return Suggestion(
id=f"connect_source:{key}",
diff --git a/products/marketing_analytics/backend/services/test_attribution_health.py b/products/marketing_analytics/backend/services/test_attribution_health.py
index 12f1e61f7335..e6fcb11ded52 100644
--- a/products/marketing_analytics/backend/services/test_attribution_health.py
+++ b/products/marketing_analytics/backend/services/test_attribution_health.py
@@ -174,10 +174,20 @@ class TestGetAttributionHealth(APIBaseTest):
assert counts == sorted(counts, reverse=True)
-def _pageview(team: object, distinct_id: str, utm_source: str | None = None) -> None:
+def _pageview(
+ team: object,
+ distinct_id: str,
+ utm_source: str | None = None,
+ utm_medium: str | None = None,
+ gclid: str | None = None,
+) -> None:
props: dict = {}
if utm_source is not None:
props["utm_source"] = utm_source
+ if utm_medium is not None:
+ props["utm_medium"] = utm_medium
+ if gclid is not None:
+ props["gclid"] = gclid
_create_event(
distinct_id=distinct_id,
event="$pageview",
@@ -352,3 +362,59 @@ class TestAttributionHealthSourceTypeFilterClickhouse(ClickhouseTestMixin, BaseT
assert response.integrations[0].integration_key == "google_ads"
assert response.total_events_with_utm == 2
assert response.total_events_matched_to_any_integration == 2
+
+
+class TestAttributionHealthPaidSignalClickhouse(ClickhouseTestMixin, BaseTest):
+ """Paid is decided the way PostHog decides it everywhere else — the channel-type
+ rule at posthog.com/docs/data/channel-type — so a `linkedin` utm_source from an
+ organic post isn't counted as ad traffic."""
+
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ _pageview(self.team, "u1", utm_source="linkedin", utm_medium="cpc")
+ _pageview(self.team, "u2", utm_source="linkedin", utm_medium="paid-social")
+ _pageview(self.team, "u3", utm_source="linkedin", utm_medium="organic-social")
+ _pageview(self.team, "u4", utm_source="linkedin")
+ _pageview(self.team, "u5", utm_source="google", gclid="abc123")
+ # A link copied from an address bar that still held a Google click id, then
+ # shared organically. The gclid names Google Ads, not LinkedIn.
+ _pageview(self.team, "u6", utm_source="linkedin", utm_medium="social", gclid="stale123")
+ flush_persons_and_events()
+
+ def tearDown(self) -> None:
+ flush_persons_and_events()
+ super().tearDown()
+
+ async def _entry(self, key: str):
+ response = await get_attribution_health(self.team, lookback_days=30)
+ return next(e for e in response.integrations if e.integration_key == key)
+
+ @pytest.mark.asyncio
+ async def test_counts_cost_bearing_and_paid_prefixed_mediums(self) -> None:
+ linkedin = await self._entry("linkedin_ads")
+
+ assert linkedin.events_matched_last_7d == 5
+ # `cpc` by name, `paid-social` by prefix. `organic-social`, the untagged one and
+ # the stale-gclid one are not paid; four of the five carry a medium.
+ assert linkedin.events_matched_paid_last_7d == 2
+ assert linkedin.events_matched_tagged_medium_last_7d == 4
+
+ @pytest.mark.asyncio
+ async def test_a_google_click_id_does_not_make_another_platform_paid(self) -> None:
+ # gclid and gad_source name Google Ads specifically, and ride along on whatever
+ # URL carries them. Crediting them to whatever utm_source they land on would put
+ # `connect LinkedIn Ads` back in front of a team that only posts there.
+ linkedin = await self._entry("linkedin_ads")
+
+ assert linkedin.events_matched_paid_last_7d == 2
+
+ @pytest.mark.asyncio
+ async def test_a_click_id_is_paid_even_with_no_medium(self) -> None:
+ # Ad platforms attach gclid; nothing else does. Requiring utm_medium here would
+ # miss every team that relies on auto-tagging.
+ google = await self._entry("google_ads")
+
+ assert google.events_matched_paid_last_7d == 1
+ assert google.events_matched_tagged_medium_last_7d == 0
diff --git a/products/marketing_analytics/backend/services/test_setup_plan.py b/products/marketing_analytics/backend/services/test_setup_plan.py
index da863268469f..44214356e744 100644
--- a/products/marketing_analytics/backend/services/test_setup_plan.py
+++ b/products/marketing_analytics/backend/services/test_setup_plan.py
@@ -44,6 +44,8 @@ def _integration(
schema_missing=None,
unmatched=0,
matched=0,
+ paid=0,
+ tagged_medium=0,
) -> IntegrationDiagnostic:
data_source = None
if status != "events_only":
@@ -82,6 +84,8 @@ def _integration(
last_event_with_matching_utm_at=None,
matched_pct=0.0,
sample_unmatched_utm_sources=[],
+ events_matched_paid_last_7d=paid,
+ events_matched_tagged_medium_last_7d=tagged_medium,
)
return IntegrationDiagnostic(
@@ -562,6 +566,61 @@ class TestConversionGoals(SetupPlanTestCase):
assert all(s.safe_to_batch is False for s in flags)
+class TestConnectSourceNeedsPaidEvidence(SetupPlanTestCase):
+ """`utm_source` maps to an ad platform on the source alone, so `google` also catches
+ gmail links and `linkedin` catches organic posts. Suggesting someone connect an ad
+ account they don't run is worse than saying nothing."""
+
+ async def _plan_for(self, *, matched=900, **kwargs):
+ # `matched`, not `unmatched`: tagged_medium is only accumulated for rows that
+ # resolved to an integration, so tagged traffic with zero matched can't happen.
+ self.diagnostic = MarketingDiagnosticResponse(
+ integrations=[_integration("linkedin_ads", "LinkedinAds", status="events_only", matched=matched, **kwargs)],
+ overall_status="broken",
+ conversion_goals=ConversionGoalsListResponse(goals=[_goal()]),
+ )
+ return await get_setup_plan(self.team)
+
+ def _connects(self, plan) -> list:
+ return [s for s in plan.suggestions if s.kind == SuggestionKind.CONNECT_SOURCE]
+
+ @pytest.mark.asyncio
+ async def test_organic_traffic_alone_does_not_ask_you_to_connect_an_ad_account(self):
+ plan = await self._plan_for(tagged_medium=900, paid=0)
+
+ assert self._connects(plan) == []
+
+ @pytest.mark.asyncio
+ async def test_paid_traffic_still_asks_you_to_connect(self):
+ plan = await self._plan_for(tagged_medium=900, paid=900)
+
+ assert len(self._connects(plan)) == 1
+
+ @pytest.mark.asyncio
+ async def test_one_paid_event_among_organic_is_enough_to_ask(self):
+ # Spend exists; the mix says the team runs both, not that it runs neither.
+ plan = await self._plan_for(tagged_medium=900, paid=1)
+
+ assert len(self._connects(plan)) == 1
+
+ @pytest.mark.asyncio
+ async def test_untagged_traffic_still_asks_because_absence_is_not_evidence(self):
+ # A team that never sets utm_medium tells us nothing either way, and staying
+ # silent there would hide the case this suggestion exists for.
+ plan = await self._plan_for(tagged_medium=0, paid=0)
+
+ assert len(self._connects(plan)) == 1
+
+ @pytest.mark.asyncio
+ async def test_a_tagged_minority_does_not_speak_for_the_untagged_rest(self):
+ # Tagged organic posts plus a larger body of untagged traffic. The untagged half
+ # is unclassified, not organic, and it's exactly where unlinked ad spend hides —
+ # so a team that tags its posts but not its ad links still gets asked.
+ plan = await self._plan_for(matched=900, tagged_medium=100, paid=0)
+
+ assert len(self._connects(plan)) == 1
+
+
class TestIntegrationSuggestions(SetupPlanTestCase):
@pytest.mark.asyncio
async def test_auth_error_becomes_a_reconnect_with_a_valid_oauth_kind(self):
diff --git a/products/marketing_analytics/frontend/generated/api.schemas.ts b/products/marketing_analytics/frontend/generated/api.schemas.ts
index fc9ade4cb2e8..ebf2e3a96187 100644
--- a/products/marketing_analytics/frontend/generated/api.schemas.ts
+++ b/products/marketing_analytics/frontend/generated/api.schemas.ts
@@ -1362,6 +1362,10 @@ export interface AttributionHealthEntryApi {
matched_pct: number
/** Sample of likely-yours unmatched utm_source values */
sample_unmatched_utm_sources: UnmatchedUtmSampleApi[]
+ /** Of the matched events, how many look paid: a cost-bearing utm_medium (cpc, cpm, cpv, cpa, ppc, retargeting, or anything starting with 'paid') or a gclid/gad_source click id. */
+ events_matched_paid_last_7d: number
+ /** Of the matched events, how many carry any utm_medium. Zero paid with a non-zero count here means the traffic is tagged and organic; both zero means the team doesn't tag medium, which says nothing. */
+ events_matched_tagged_medium_last_7d: number
}
export interface RecommendedActionApi {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 684b6e82754f..941bbded0777 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10257,6 +10257,10 @@ export namespace Schemas {
matched_pct: number;
/** Sample of likely-yours unmatched utm_source values */
sample_unmatched_utm_sources: UnmatchedUtmSample[];
+ /** Of the matched events, how many look paid: a cost-bearing utm_medium (cpc, cpm, cpv, cpa, ppc, retargeting, or anything starting with 'paid') or a gclid/gad_source click id. */
+ events_matched_paid_last_7d: number;
+ /** Of the matched events, how many carry any utm_medium. Zero paid with a non-zero count here means the traffic is tagged and organic; both zero means the team doesn't tag medium, which says nothing. */
+ events_matched_tagged_medium_last_7d: number;
}
export type AttributionMode = typeof AttributionMode[keyof typeof AttributionMode];